Breadth-First Search
Explore level by level with a queue - shortest paths when every edge costs the same.
- waiting / queued
- active this step
- current
- visited / done
- result
Start at A
A is 0 steps from itself and is the only node in the queue.
VARIABLES
- node
- -
- queue
- [A]
- dist
- {A: 0}
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
BFS visits the start, then all its neighbours, then theirs, using a queue. The first time it reaches a node is along a shortest path in an unweighted graph.
Why it matters
Shortest-path and minimum-steps questions on unweighted graphs and grids are BFS by default.
Think of it like this
Ripples in a pond: the circle reaches nearer points before farther ones.
Use it when
- Minimum number of steps or moves
- Level order traversal
- Things spreading each minute - rotting oranges, fire
Avoid it when
- Edges with different costs - use Dijkstra
- You need to follow one path deeply - DFS is lighter
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| BFS on a graph | O(V + E) | O(V) |
| BFS on an r × c grid | O(r × c) | O(r × c) |
| Each enqueue or dequeue | O(1) | - |
Often confused with: DFS - it reaches every node too, but not along shortest paths.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Mark nodes visited when you enqueue them, not when you dequeue them
- Multi-source BFS: put every start in the queue first
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Marking nodes visited on dequeue - the same node gets queued many times
- Using a list with pop(0) as the queue
- Forgetting grid bounds or obstacle checks
Edge cases to test
- Start equals goal - distance 0
- Goal unreachable - return -1
- A disconnected graph
Knowledge check
Quick check to lock in the intuition.
Edges now have different weights (1, 5, 2…). Is BFS still correct for shortest paths?
Practice
Apply what you just watched on real interview problems.