Graphs
Start at node 0 with distance 0. Everyone else is ∞ — undiscovered.
1 / 32How breadth-first search works
BFS explores in rings: first everything one edge from the start, then everything two edges away, and so on. The queue is what enforces the fairness — nodes are processed in the order they were discovered, so no node at distance 3 is touched before every node at distance 2 is done. Watch the dist labels: they only ever come out in non-decreasing order.
That ring discipline is the proof of BFS's headline guarantee: in an unweighted graph, the first time you reach a node is via a fewest-edges path. The moment a node gets a distance, it is final — no later discovery can beat it. This is why every “minimum number of moves/steps/transformations” problem (word ladder, knight moves, sliding puzzle) is secretly a BFS.
The check that guards everything: only enqueue a node if it has never been seen (dist still ∞). Mark it seen when you enqueue, not when you dequeue — the classic bug is marking late, which lets the same node enter the queue twice. Swap the queue for a stack and this exact code becomes DFS; the data structure is the strategy.
space play / pause · ←→ step
Complexity
| time | O(V + E) |
|---|---|
| space | O(V) |
| finds | fewest-edge paths |
| frontier | FIFO queue |