Track progress, take quizzes and save notes on this lesson.

Free forever · no card needed

Start free
Intermediate

Graph Traversal: BFS and DFS

4.3.1.1 Simple graph-traversal algorithms

Aligned to the AQA 7517 specification

Level
Intermediate
Reading time
8 min
Published
6 June 2026
Updated
1 July 2026
On this page
  1. 1.What Is Graph Traversal?
  2. 2.Breadth-First Search
  3. 3.Tracing BFS
  4. 4.Depth-First Search
  5. 5.Tracing DFS
  6. 6.Applications: Choosing BFS or DFS
  7. 7.Common Exam Mistakes

Key takeaways

  • Breadth-first search (BFS) uses a queue (FIFO) to explore a graph level by level from the source, while depth-first search (DFS) uses a stack (LIFO) or recursion to go as deep as possible along one branch before backtracking.
  • Both BFS and DFS maintain a visited set so each reachable vertex is processed once; without it the traversal loops indefinitely in any graph containing cycles.
  • In BFS a vertex is marked visited when it is added to the queue, not when it is dequeued, to stop it being enqueued more than once.
  • BFS guarantees the shortest path by edge count from the source in an unweighted graph; in a weighted graph use Dijkstra's algorithm because fewer edges can still mean higher total cost.
  • DFS suits maze navigation and is also used for detecting cycles, topological sorting, and checking graph connectivity.

What Is Graph Traversal?

A graph is a data structure consisting of vertices (nodes) connected by edges (arcs). Graphs can be undirected, directed, or weighted. A graph traversal visits every reachable vertex exactly once, following edges from a chosen starting vertex.

Two traversal algorithms are required for AQA A-Level: breadth-first search (BFS) and depth-first search (DFS). They differ in the order they explore the graph — and that difference determines which problems each one solves.

Both algorithms maintain a visited set to ensure no vertex is processed twice. Without this, the traversal would loop indefinitely in any graph containing cycles.

AlgorithmData structureExploration order
BFSQueue (FIFO)Level by level from source — all vertices at distance 1, then distance 2, then distance 3, …
DFSStack (LIFO) or recursionAs deep as possible along one branch before backtracking

The graph used throughout this lesson:

Edges: A–B, A–C, B–D, B–E, C–F. Starting vertex: A.

Breadth-First Search

Breadth-first search explores all vertices one edge from the source, then all vertices two edges away, and so on. It works outward in layers.

The algorithm:

  1. Add the starting vertex to the queue. Mark it visited.
  2. Dequeue the front vertex. For each of its unvisited neighbours: mark visited, enqueue.
  3. Repeat until the queue is empty.

Vertices are marked visited when they are added to the queue — not when they are dequeued. This prevents a vertex from being added to the queue more than once if it has multiple neighbours that have already been processed.

BFS(graph, start):
    queue = [start]
    visited = {start}
    WHILE queue is not empty:
        vertex = Dequeue(queue)
        OUTPUT vertex
        FOR EACH neighbour OF vertex:
            IF neighbour NOT IN visited:
                visited.add(neighbour)
                Enqueue(queue, neighbour)

Because BFS processes vertices in order of their distance from the source, the first time it reaches a vertex it has taken the fewest possible edges to get there. This is the basis for its use in shortest-path problems.

Tracing BFS

Starting from A on the graph above:

StepDequeueUnvisited neighbours added to queueQueue after stepVisited
1AB, C[B, C]{A, B, C}
2BD, E (A already visited)[C, D, E]{A, B, C, D, E}
3CF (A already visited)[D, E, F]{A, B, C, D, E, F}
4Dnone[E, F]
5Enone[F]
6Fnone[]

BFS visit order: A, B, C, D, E, F

The traversal visits A first (distance 0), then B and C (distance 1), then D, E, and F (distance 2). No vertex at distance 2 is visited before all vertices at distance 1 — this is the level-by-level guarantee of the queue.

The shortest path in terms of edges from A to any vertex is the path BFS took to first reach it:

  • A → B (1 edge)
  • A → C (1 edge)
  • A → B → D (2 edges)
  • A → C → F (2 edges)

Depth-First Search

Depth-first search follows one branch as far as it will go, then backtracks to explore alternative routes. Instead of spreading outward, it plunges downward.

DFS is naturally implemented recursively — the call stack handles the backtracking automatically:

DFS(graph, vertex, visited):
    visited.add(vertex)
    OUTPUT vertex
    FOR EACH neighbour OF vertex IN alphabetical order:
        IF neighbour NOT IN visited:
            DFS(graph, neighbour, visited)

The key behavioural difference from BFS: DFS commits fully to the first neighbour it visits, exhausting that entire branch before returning to try the next alternative. There is no "level" structure — the algorithm only backtracks when it reaches a vertex with no unvisited neighbours.

An iterative version using an explicit stack is equivalent, but the recursive form most clearly shows the backtracking logic.

Studying this for an exam?

Generate a personalised learning path for this subject. Free to get started.

Create a learning path

Tracing DFS

Starting from A on the same graph, visiting neighbours alphabetically:

StepVisitAction
1AA's neighbours: B, C. Visit B first.
2BB's unvisited neighbours: D, E (A visited). Visit D first.
3DD has no unvisited neighbours. Backtrack to B.
4EB's next unvisited neighbour. E has no unvisited neighbours. Backtrack to B → backtrack to A.
5CA's next unvisited neighbour. C's unvisited neighbours: F (A visited). Visit F.
6FF has no unvisited neighbours. Done.

DFS visit order: A, B, D, E, C, F

Compare with BFS order (A, B, C, D, E, F): DFS finished the entire B branch (D, E) before visiting C. BFS visited B and C at the same level before going deeper.

The same visited set protects DFS from cycles — if the graph contained an edge from D back to A, step 3 would check A and skip it (already visited).

Applications: Choosing BFS or DFS

The structural difference between the two algorithms determines which problems each one solves.

BFS — shortest path in an unweighted graph:

Because BFS reaches each vertex via the fewest possible edges, it guarantees the shortest path (by edge count) from the source to any reachable vertex in an unweighted graph. This is its primary application.

DFS — navigating a maze:

DFS models the strategy of following a corridor until you hit a dead end, then backtracking to try another route. It is the natural algorithm for maze-solving. DFS is also used for detecting cycles, topological sorting, and checking graph connectivity.

ApplicationAlgorithmWhy
Shortest path (unweighted graph)BFSLevel-by-level order guarantees minimum edges
Maze navigation / path explorationDFSFollows one route to its end before trying alternatives
Finding all reachable verticesEitherBoth visit every reachable vertex exactly once
Detecting whether a path existsEitherBoth determine reachability

BFS only guarantees the shortest path in unweighted graphs. In a weighted graph, the path with fewer edges can have a higher total cost. Use Dijkstra's algorithm for weighted shortest paths.

Common Exam Mistakes

1. Marking vertices visited at the wrong point in BFS

Mark a vertex visited when it is added to the queue, not when it is dequeued. If you wait until dequeue, a vertex with two neighbours that have already been processed can be added to the queue twice, producing an incorrect trace.

2. Claiming BFS finds shortest paths in weighted graphs

BFS minimises edge count, not total weight. "Fewer edges" and "shorter path" are only equivalent when all edge weights are equal. For weighted graphs, the shortest path requires Dijkstra's algorithm.

3. Confusing the visit order of BFS and DFS

In a trace question: if all vertices at distance 1 are visited before any at distance 2, the traversal is BFS. If the algorithm finishes one branch entirely before returning to the next, it is DFS. Identify the pattern from the sequence, not from labelling alone.

4. Forgetting the visited set

In any graph with cycles, omitting the visited check causes infinite loops. Every vertex must be tracked when added (BFS) or when first reached (DFS). Exam trace questions frequently test whether you skip an already-visited neighbour at the correct step.

5. Assuming graph traversal only applies to trees

A tree is a special case of a graph (connected, undirected, no cycles). BFS and DFS apply to any graph — including those with cycles, disconnected components, or directed edges. If the graph is not fully connected, a single traversal from one start vertex will not reach all vertices.

Key terms

Graph
A data structure of vertices (nodes) connected by edges (arcs), which can be undirected, directed, or weighted.
Graph traversal
Visiting every reachable vertex exactly once by following edges from a chosen starting vertex.
Breadth-first search (BFS)
A traversal using a queue (FIFO) that explores the graph level by level from the source.
Depth-first search (DFS)
A traversal using a stack (LIFO) or recursion that follows one branch as far as possible before backtracking.
Visited set
The record of already-processed vertices that ensures no vertex is visited twice and prevents infinite loops in cyclic graphs.
Queue (FIFO)
A first-in, first-out structure used by BFS to process vertices in order of distance from the source.
Stack (LIFO)
A last-in, first-out structure (or the recursive call stack) used by DFS to handle backtracking.
Backtracking
Returning to a previous vertex in DFS to try another route once a branch has no unvisited neighbours.

Frequently asked questions

BFS uses a queue to explore a graph level by level, visiting all vertices at distance 1 before distance 2, and so on. DFS uses a stack or recursion to follow one branch as deep as possible before backtracking. BFS spreads outward; DFS plunges downward.

Mark a vertex visited when it is added to the queue, not when it is dequeued. If you wait until it is dequeued, a vertex with two already-processed neighbours can be added to the queue twice, producing an incorrect trace.

BFS guarantees the shortest path by edge count only in an unweighted graph, because it reaches each vertex via the fewest edges. In a weighted graph the path with fewer edges can have a higher total cost, so Dijkstra's algorithm is needed instead.

Generate revision on any topic you study

Type any topic you're studying and Aicademy generates a complete lesson, quiz, and flashcard set, personalised to your level.

Lessons on anything

Structured, level-matched lessons on any topic you study

Practice quizzes

Find out what you actually know before the exam does

Flashcard sets

Lock in key concepts with instant revision cards

Ask Aica

Stuck on something? Get a clear explanation, any time

Next

Reverse Polish Notation

Related lessons

5 min

Lesson

Graphs

A-Level Computer Science · AQA 7517

1 month ago

8 min

Lesson

Binary Search Trees

A-Level Computer Science · AQA 7517

1 month ago

9 min

Lesson

Stacks and Queues

A-Level Computer Science · AQA 7517

2 months ago

Top students don’t revise more. They revise what counts.

Start revising free

Free to start. No card needed.