Why BFS Finds Shortest Paths
The previous lesson claimed that breadth-first search computes, for every vertex, the smallest number of edges on a path from the source. That is plausible from the picture of waves, but the picture hides the actual reason, which is a property of the queue. This lesson states the claim precisely and proves it in four steps, then tests every step on random graphs and shows what breaks when the queue is replaced by a stack.
The claim
Define the shortest-path distance as the minimum number of edges on any path from to , or if no path exists. A path from to of length is a shortest path. The theorem:
When BFS terminates, for every vertex . Moreover, for every reachable , a shortest path from to is a shortest path from to followed by the edge .
It holds for directed and undirected graphs alike. The proof needs three lemmas.
Step 1: one edge changes the distance by at most one
Lemma 1. For every edge , .
If is unreachable the right side is . Otherwise a shortest path to followed by the edge is a path to with edges, and the shortest path to is no longer than that.
Step 2: BFS never underestimates
Lemma 2. At every moment during BFS, for every vertex .
Induction on the number of ENQUEUE operations. Initially and every other . The only assignment is when is discovered from . By induction , so by Lemma 1. Since is enqueued only once, its never changes again.
Step 3: the queue is sorted, with a spread of at most one
Lemma 3. Whenever the queue holds (head , tail ),
Induction on queue operations. With only in the queue it is trivial. Dequeue: removing leaves as the head. The chain of inequalities is still sorted, and . Enqueue: a new vertex is discovered from , the vertex just dequeued, so . Before left, it was the head, so by induction every queued vertex had : the new tail has the largest value, and the sequence stays sorted. The new head was behind , so , and .
Corollary. If is enqueued before , then at the moment is enqueued. Vertices enter the queue in non-decreasing order of , which is the precise form of "waves".
Step 4: the theorem
Suppose some vertex ends with . Among all such vertices pick one with the smallest . By Lemma 2, , so is finite and . Let be the vertex just before on a shortest path from to . Then , and by the choice of , . So
Now look at the moment BFS dequeues , which it does since is reachable. Vertex is in one of three states. If it is still undiscovered, line 8 sets : contradiction. If it was already dequeued, it entered the queue before , so by the corollary: contradiction. If it is in the queue, it was discovered from some dequeued before , so : contradiction. Hence for all . The statement about follows because and both values are now exact.
Testing the lemmas
The program runs BFS on 300 random directed graphs, checks Lemma 3 after every queue operation, and compares every final with a brute-force distance: the number of rounds of "extend all known paths by one edge" needed to reach .
from collections import deque
import random
def random_digraph(rng, n, p):
return {u: [v for v in range(n) if v != u and rng.random() < p] for u in range(n)}
def bfs_checked(adj, s):
d = {v: float("inf") for v in adj}
d[s] = 0
q = deque([s])
checks = 0
while q:
u = q.popleft()
for v in adj[u]:
if d[v] == float("inf"):
d[v] = d[u] + 1
q.append(v)
vals = [d[x] for x in q]
assert all(a <= b for a, b in zip(vals, vals[1:])), "queue not sorted"
assert not vals or vals[-1] <= vals[0] + 1, "spread above one"
checks += 1
return d, checks
def brute(adj, s):
dist, frontier, k = {s: 0}, {s}, 0
while frontier:
k += 1
frontier = {v for u in frontier for v in adj[u] if v not in dist}
for v in frontier:
dist[v] = k
return {v: dist.get(v, float("inf")) for v in adj}
rng = random.Random(2024)
total_checks = vertices = 0
for trial in range(300):
n = rng.randint(2, 30)
adj = random_digraph(rng, n, rng.choice([0.05, 0.1, 0.3]))
d, c = bfs_checked(adj, 0)
assert d == brute(adj, 0)
total_checks += c
vertices += n
print(f"300 graphs, {vertices} vertices: every BFS distance equals the brute-force distance")
print(f"Lemma 3 held at all {total_checks} queue checks")300 graphs, 4857 vertices: every BFS distance equals the brute-force distance
Lemma 3 held at all 12474 queue checks
What breaks with a stack
The queue's first-in, first-out order is what Lemma 3 is about. Replace it with a stack (last in, first out) and keep everything else, and the "distances" become the lengths of whatever paths the search happened to follow first. On this graph the stack version takes the long way round to :
adj = {"A": ["B", "D"], "B": ["C"], "C": [], "D": ["E"], "E": ["C"]}
def search(adj, s, use_queue):
d = {s: 0}
frontier = [s]
while frontier:
u = frontier.pop(0) if use_queue else frontier.pop()
for v in adj[u]:
if v not in d:
d[v] = d[u] + 1
frontier.append(v)
return d
print("queue (BFS):", search(adj, "A", True))
print("stack: ", search(adj, "A", False))queue (BFS): {'A': 0, 'B': 1, 'D': 1, 'C': 2, 'E': 2}
stack: {'A': 0, 'B': 1, 'D': 1, 'E': 2, 'C': 3}
With the stack, (pushed last) is expanded before , its neighbour before , and discovers at "distance" 3, although has length 2. The same mistake happens with weights: BFS minimizes the number of edges, not the total weight. For weighted graphs the right tool is Dijkstra's algorithm, whose correctness proof follows exactly the pattern of Step 4, with a priority queue in place of the FIFO queue.
Note: If all edges have weight 0 or 1, a deque gives shortest weighted paths in : push a vertex reached by a 0-edge on the front and one reached by a 1-edge on the back. The deque then stays sorted by tentative distance with a spread of at most one, the analogue of Lemma 3, and a vertex is final when it leaves the front. This "0-1 BFS" is a handy special case of Dijkstra.
Test yourself
Which property of the BFS queue is the heart of the correctness proof?
- It never holds more than two vertices
- Its values are non-decreasing from head to tail and differ by at most 1
- It is empty at every level boundary
- Every vertex is enqueued twice
Lemma 2 says at all times. What does that alone guarantee?
- That BFS terminates
- That BFS never reports a distance shorter than the true one
- That every vertex is reached
- That the parent pointers form a tree
In the proof of the theorem, why is chosen with the smallest among the wrong vertices?
- So that its predecessor on a shortest path has a correct
- So that is a leaf
- So that is the source
- So that the queue is empty
BFS is run on a weighted graph, ignoring the weights. What does give?
- The least total weight from
- The fewest edges on a path from
- The largest weight on any path
- Nothing meaningful