Graph traversal: BFS and DFS

In one sentence

BFS explores level by level with a queue and finds shortest paths when every edge costs the same; DFS goes deep with a stack or recursion; with a visited set, both are O(V + E).

BFS: a FIFO queue pops nodes in distance order; marking on push keeps each node in the queue once. Swap the queue for a stack and you get DFS.

How it works

  • Model the input as a graph: in a grid, a cell's neighbors are its 4 adjacent cells.
  • BFS reaches nodes in distance order, so the first hit is the shortest unweighted path.
  • DFS explores everything reachable: components, flood fill, cycles, topological order.
  • Mark visited on push, not on pop, so each node enters once: O(V + E).
  • Directed cycle: a neighbor still on the current DFS path. Undirected: a visited neighbor that isn't the parent.

Check yourself

Answer to mark it learned; your answers aren't scored.

Find the fewest single-letter changes that turn cold into warm, where every intermediate word must be in a 50k-word dictionary. What is the simplest correct approach?

Go deeper

Solve it in Python 10
Full explanation

First model the input as a graph: nodes plus a way to list neighbors. A grid is a graph whose neighbors are the 4 adjacent cells; in a word ladder, neighbors differ by one letter.

  • BFS uses a queue (collections.deque). It reaches nodes in order of distance, so the first time you reach the target is the shortest path in an unweighted graph. Seed the queue with many sources for multi-source problems (distance to the nearest exit).
  • DFS uses recursion or an explicit stack. It suits 'explore everything reachable': connected components, flood fill, path existence, cycle detection and Topological sort.

Both need a visited set, marked when a node is pushed, not when it is popped, so each node enters once. To count components, start a traversal from every unvisited node.

Cycles: in an undirected graph, a visited neighbor that isn't your parent; in a directed graph, a neighbor still on the current DFS path (gray).

Code Grid BFS (fewest steps) and iterative DFS (components)
pythonGrid BFS (fewest steps) and iterative DFS (components)
from collections import deque

def grid_bfs(grid, start, goal):              # 0 = open, 1 = wall
    rows, cols = len(grid), len(grid[0])
    q, seen = deque([(start, 0)]), {start}
    while q:
        (r, c), d = q.popleft()
        if (r, c) == goal:
            return d                           # first hit = fewest steps
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            inside = 0 <= nr < rows and 0 <= nc < cols
            if inside and grid[nr][nc] == 0 and (nr, nc) not in seen:
                seen.add((nr, nc))             # mark on push: queued once
                q.append(((nr, nc), d + 1))
    return -1                                  # unreachable

def count_components(n, adj):
    seen, count = set(), 0
    for s in range(n):
        if s not in seen:                      # new component: flood it
            count += 1
            seen.add(s)
            stack = [s]                        # explicit stack: no recursion limit
            while stack:
                for nb in adj[stack.pop()]:
                    if nb not in seen:
                        seen.add(nb)
                        stack.append(nb)
    return count
Real example

Number of islands on a 1,000 × 1,000 grid of land and water. Scan every cell; each unvisited land cell starts a traversal that marks its whole island, and the count goes up by one. Each cell is visited once and checks 4 neighbors: ~10⁶ cells, ≤ 4·10⁶ checks. A recursive DFS on one long snake-shaped island can go hundreds of thousands of calls deep, past CPython's default limit of 1,000, so use an explicit stack or BFS.

Trade-offs +3 · −2

+ You gain

  • Linear time, O(V + E), in about 15 lines.
  • BFS gives shortest paths for free when every edge costs the same.
  • One template covers grids, trees and implicit graphs such as puzzle states.

− You pay

  • BFS memory grows with the widest level: up to O(V) for the frontier.
  • Recursive DFS hits the recursion limit on deep graphs.

Use it when

BFS: minimum steps or moves, nearest X, level order, multi-source spread. DFS: reachability, components, flood fill, cycle detection, topological order, exhaustive path search.

Avoid it when

Edges with different weights: use Dijkstra (Shortest Paths (BFS, Dijkstra, Bellman-Ford)). Many connectivity queries while edges keep arriving: Union-Find (Disjoint Set Union) is simpler.

Numbers to know 4
  • Time O(V + E) with adjacency lists; O(V²) with an adjacency matrix.
  • Grid R × C: R·C nodes and ≤ 4·R·C neighbor checks.
  • Space O(V) for the visited set; the BFS queue holds up to the widest level.
  • CPython's default recursion limit: 1,000 frames (sys.getrecursionlimit()).
Common pitfalls 4
  • Marking visited on pop: a node can be queued once per incoming edge and expanded again and again.
  • Using list.pop(0) as the queue: O(n) per pop. Use collections.deque.
  • Recursive DFS on a 10⁶-cell grid: RecursionError. Use an explicit stack.
  • Using BFS on weighted edges: the fewest edges is not the cheapest path.
Interview questions 3

Answer out loud first, then reveal.

BFS or DFS: how do you choose?Show answer

If the question says minimum steps, nearest something, or shortest path with equal costs, I use BFS: it explores by distance, so the first hit is optimal. If it's reachability, components, cycles or ordering, both work and I pick DFS because it's shorter, written with an explicit stack when depth can be large. If edges have different weights, neither: that's Dijkstra.

How do you detect a cycle?Show answer

Undirected: during DFS, a visited neighbor that isn't the node I came from closes a cycle; union-find also works. Directed: I color nodes white, gray while on the current path, and black when done. Reaching a gray node is a back edge, so a cycle. Reaching a black node is fine: two paths can share a descendant without a cycle. Kahn's algorithm is the iterative alternative.

Which BFS and DFS variants should you know?Show answer

Multi-source BFS: seed every source at distance 0. 0-1 BFS: a deque, pushing weight-0 edges to the front, when edges cost 0 or 1. Bidirectional BFS: search from both ends when start and goal are known, to explore far fewer nodes. BFS over implicit states, like lock combinations or word ladders. And DFS with backtracking when I need every path, not just one.