Interview patterns
BFS Pattern Explained: Explore Level by Level for the Shortest Path
Updated Dec 2, 2026 · 4 min read
Breadth-first search explores a graph or grid one level at a time with a queue: first everything 1 step from the start, then everything 2 steps away, and so on. When every move costs the same, the first time you reach the target is the shortest path. It runs in O(V + E) time.

Key points
- ●Spot it when the problem asks for the shortest path, fewest steps or minimum moves and every move costs the same.
- ●Other clues: level by level, layers, or something spreading from several sources at once.
- ●Use a queue and process one whole level per loop, then add 1 to the step count.
- ●Mark a node seen when you push it, not when you pop it.
- ●Practice on 102, 200, 994, 127 and 1091.

The problem: a path that isn't the shortest
You're in a small maze and need the fewest moves from the start to the exit. A depth-first search will happily find a path: it runs down one corridor as far as it can, backs up, tries the next. On an open 4 by 4 grid it can snake row by row and take 12 steps to reach a corner that's only 6 steps away.
DFS answers "is there a path?". It doesn't answer "what's the shortest one?". For that you want breadth-first search.
When to spot it
The "When to Spot BFS" list on the visual sheet above gives the clues:
- The problem asks for a shortest path, fewest steps or minimum moves on an unweighted grid or graph.
- The wording says level by level, or layer.
- Something spreads over time from several sources at once, like rot, fire or infection.
- The input is a grid, a tree, or a graph of states such as words or lock combinations.
- States connect by one-move steps that all cost the same.
The sheet also lists when not to use it: weighted edges call for Dijkstra, and needing every path rather than the shortest calls for DFS or backtracking.
The idea: one ring at a time
Put the start in a queue. Then repeat: take every node currently in the queue (that's one level), and push each unseen neighbor. When the level is done, add 1 to the step count.
Picture ripples on water. Ring 1 is everything one move away, ring 2 is everything two moves away. Because rings grow in order, the first ring that touches the target gives you the shortest distance.
Worked example
A 3 by 3 grid, where 0 is open and 1 is a wall:
| Row | Col 0 | Col 1 | Col 2 |
|---|---|---|---|
| 0 | 0 (start) | 0 | 0 |
| 1 | 1 | 1 | 0 |
| 2 | 0 | 0 | 0 (exit) |
Moves are up, down, left and right. The middle row is a wall with one gap on the right.
| Level | Cells reached | Note |
|---|---|---|
| 0 | (0,0) | the start |
| 1 | (0,1) | (1,0) is a wall |
| 2 | (0,2) | the top right corner |
| 3 | (1,2) | through the gap |
| 4 | (2,2) | the exit |
The answer is 4 steps, which matches the "Worked Example Answer" box on the sheet.
The Python template
from collections import deque
def bfs(start, target):
q, seen, steps = deque([start]), {start}, 0
while q:
for _ in range(len(q)):
node = q.popleft()
if node == target:
return steps
for nxt in neighbors(node):
if nxt not in seen:
seen.add(nxt)
q.append(nxt)
steps += 1
return -1
neighbors(node) is whatever the problem defines: the four open cells around a grid cell, the children of a tree node, or every word one letter away. The inner for loop runs exactly one level, which is what keeps steps correct. If the queue empties without reaching the target, there's no path and it returns -1.
Complexity
Each node is queued once and each edge is looked at once, so the time is O(V + E). On an m by n grid that's O(m * n). The queue and the seen set hold at most V nodes, so the space is O(V).
The trap: seen on pop
The Golden Rule box on the sheet is the bug most people hit: mark a node seen when you push it, not when you pop it. If you wait for the pop, a cell with three open neighbors can be pushed three times before it's ever processed. The answer often still comes out right, but the queue blows up and big grids time out.
Two smaller traps: forgetting to check walls and grid bounds in neighbors, and using BFS on weighted edges, where the first hit is no longer the cheapest.
Problems to practice
- 102 Binary Tree Level Order Traversal: the template without a target, collecting each level.
- 200 Number of Islands: run BFS from every unvisited land cell and count the runs.
- 994 Rotting Oranges: start the queue with every rotten orange at once; the levels are the minutes.
- 127 Word Ladder: the nodes are words, the neighbors are words one letter away.
- 1091 Shortest Path in Binary Matrix: the grid example with eight directions instead of four.
Frequently asked questions
Why does BFS find the shortest path?
BFS reaches every node at distance 1 before any node at distance 2, every node at distance 2 before distance 3, and so on. So the first time it reaches the target, no shorter route can exist. This only holds when every move costs the same.
What is the time complexity of BFS?
O(V + E), where V is the number of nodes and E the number of edges, because each node enters the queue once and each edge is checked once. On an m by n grid that is O(m * n). The queue and the seen set take O(V) space.
When should I use DFS instead of BFS?
Use DFS or backtracking when you need every path, or just whether any path exists, and the length doesn't matter. Use BFS when you need the shortest one in an unweighted graph. With weighted edges, neither is right: use Dijkstra.
Why mark nodes as seen when pushing instead of popping?
If you wait until a node is popped, several of its neighbors can push it before that happens, so the same cell sits in the queue many times. Marking it on push means it can only be queued once.