Breadth-first search & shortest paths
◈ 5 cardsBFS computes unweighted shortest-path distances in Θ(V+E); the queue is the gray frontier.
What BFS computes
Given a graph and a source , breadth-first search discovers every vertex reachable from and computes , the minimum number of edges on any -to- path. It also builds a breadth-first tree via parent pointers , and that tree's -to- path is a shortest path.
BFS uses three colours: white (undiscovered), gray (discovered, frontier), black (fully explored). The central invariant: the FIFO queue holds exactly the gray vertices — the boundary between explored and unexplored. Because the queue is FIFO, BFS expands level by level: all distance-1 vertices before any distance-2 vertex.
The algorithm
Initialise every vertex white with , set , gray , enqueue it. Then repeatedly dequeue a vertex and scan its neighbours: each white neighbour gets , , turns gray, and is enqueued. When 's list is exhausted, turns black.
Why (aggregate analysis). Initialisation is . Each vertex is enqueued and dequeued at most once — the white-check before enqueueing guarantees it — so all queue operations total . Each adjacency list is scanned exactly once, when its owner is dequeued, summing to . Total: .
Worked example
On the CLRS grid graph with source , BFS assigns distances ; ; ; . To recover a path, follow pointers from the target back to and reverse: the path to is , length . PRINT-PATH does this recursively — recurse to first, print on the way out, so the path prints in forward order in .