Breadth-First Search (BFS) and Depth-First Search (DFS): Concepts and Worked Examples

Breadth-First Search (BFS) and Depth-First Search (DFS): Concepts and Worked Examples

Verified Sources
Nov 4, 2026

Breadth-First Search BFS and Depth-First Search DFS are two foundational strategies for exploring graphs graph.

At a high level:

  • BFS explores the graph in layers (all nodes at distance kk from the start are visited before distance k+1k+1), which makes it ideal for finding shortest paths in unweighted graphs.
  • DFS explores by going deep first, which is useful for tasks like connectivity checking and cycle detection (with the right bookkeeping).

The key implementation idea is the data structure:

  • BFS uses a queue (FIFO) to ensure “level-order” expansion.
  • DFS uses a stack behavior (explicit stack or recursion) to ensure “deep-first” expansion.

Important: I attempted to run web searches to support every major claim with citations, but the web-search tool is currently unavailable due to plan/quota limits. As a result, I cannot include the required external citations/footnotes for this response.


Breadth-First Search (BFS) — step-by-step

  1. 1
    Step 1

    Select a source vertex ss. Initialize a queue with ss.

  2. 2
    Step 2

    Mark ss as visited, then push it into the queue.

  3. 3
    Step 3

    While the queue is not empty, pop the front vertex uu and iterate over its adjacency list.

  4. 4
    Step 4

    For each neighbor vv of uu, if vv is unvisited, mark it visited, record its parent/level if needed, and enqueue vv.

  5. 5
    Step 5

    "When the queue empties, BFS has visited the reachable component from ss, producing a BFS tree."

    Keywords: queue, adjacency list, BFS tree.

Depth-First Search (DFS) — step-by-step

  1. 1
    Step 1

    Select a source vertex ss. Initialize an empty stack (if iterative) or start recursion at ss.

  2. 2
    Step 2

    Mark ss visited and push it onto the stack (iterative) or call DFS(s) (recursive).

  3. 3
    Step 3

    From the top of the stack (or current recursion frame), pick an unvisited neighbor vv.

  4. 4
    Step 4

    Mark vv visited, then either recurse into vv or push vv onto the stack.

  5. 5
    Step 5

    If all neighbors are visited, backtrack (return from recursion or pop the stack).

  6. 6
    Step 6

    "DFS ends after exploring as deep as possible along every branch in the reachable component."

    Keywords: stack, backtracking, DFS tree.

Worked Example Graph

Let’s use the same undirected graph for both BFS and DFS traversals:

Vertices: {A,B,C,D,E,F,G}\{A,B,C,D,E,F,G\}

Edges:
AA connected to B,CB,C
BB connected to D,ED,E
CC connected to FF
DD connected to GG
EE connected to GG
FF connected to EE
(Assume adjacency lists are processed in alphabetical order for determinism.)

BFS example (from AA)

With BFS, we visit nodes by increasing distance from AA:

  • Distance 0: AA
  • Distance 1: B,CB, C
  • Distance 2: D,E,FD, E, F
  • Distance 3: GG

One consistent BFS order (depending on adjacency iteration order) is: A,  B,  C,  D,  E,  F,  GA,\; B,\; C,\; D,\; E,\; F,\; G

Why BFS yields shortest paths in unweighted graphs:
When BFS first discovers a vertex vv, it has found a path from ss using the minimum number of edges—because BFS explores all vertices at distance kk before any at distance k+1k+1.

DFS example (from AA)

With DFS (alphabetical neighbor order), DFS goes deep before backtracking:

Starting at AA:

  • Visit AA, then go to BB
  • From BB, go to DD
  • From DD, go to GG
  • Backtrack; from BB next go to EE
  • From EE, GG is already visited; backtrack
  • Back to AA, next go to CC
  • From CC, go to FF
  • From FF, neighbor EE already visited; backtrack and finish

A consistent DFS visitation order is: A,  B,  D,  G,  E,  C,  FA,\; B,\; D,\; G,\; E,\; C,\; F

DFS does not guarantee shortest paths; it guarantees a systematic exploration pattern.

BFS vs DFS: traversal behavior (intuition)

Qualitative comparison for the same start node and neighbor ordering.

Visual intuition (BFS layers vs DFS deep dives)

Common pitfalls and edge cases

Pro Tip

To reconstruct an actual path with BFS, store a parent pointer when you discover each node. Then backtrack from the target to the start.

Warning: recursion depth vs iterative DFS

Recursive DFS may overflow the call stack on very large graphs or deep recursion paths. Iterative DFS using an explicit stack is safer in production systems.

How these traversals are commonly taught/used

Graph model

1. Representation

Choose adjacency list/matrix and define neighbors."

Queue (BFS) vs stack (DFS)

2. Core mechanism

Select the data structure and the visited rule."

BFS levels vs DFS discovery path

3. Interpretation

Use BFS levels for shortest paths; use DFS tree for deep structure."

Shortest paths / components / cycles

4. Applications

BFS: shortest unweighted paths; DFS: topology & cycle detection (with extra logic)."

1from collections import deque 2 3def bfs(graph, start): 4 visited = set([start]) 5 parent = {start: None} 6 q = deque([start]) 7 8 order = [] 9 while q: 10 u = q.popleft() 11 order.append(u) 12 for v in graph[u]: 13 if v not in visited: 14 visited.add(v) 15 parent[v] = u 16 q.append(v) 17 return order, parent

Knowledge Check

Question 1 of 4
Q1Single choice

Which data structure is most associated with Breadth-First Search?

Note on citations

"This output could not include the mandatory external citations because the web-search tool returned quota/plan errors during research. If you enable web access, I can regenerate the section with full source-backed claims and footnotes."

Footnotes