Memra

Breadth-first search & shortest paths

◈ 5 cards

BFS 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 .

sd=0rd=1wd=1vd=∞td=∞xd=∞Queue = [r, w] = the gray set.
Round 1. s has been dequeued and its list scanned, so r and w are discovered (gray, d = 1) and queued. The queue holds exactly the gray vertices — the frontier between explored and unexplored.
sd=0rd=1wd=1vd=2td=2xd=2Queue = [v, t, x] — level 2.
Round 2. Dequeuing r then w discovers the whole d = 2 layer in one go. FIFO order is what guarantees it: every distance-1 vertex is dequeued before any distance-2 vertex. (u and y, at d = 3, are off-figure.)
sd=0rd=1vd=2wd=1td=2ud=3xd=2yd=3
Following π back from u and reversing gives s → w → t → u: three edges, exactly δ(s,u) = 3. Every root-to-vertex path in this tree is a shortest path.
NORMAL ~/memra/learn/comp-372/breadth-first-search utf-8 LF