TExcelTAD
Home › Graph Algorithms › Why BFS Finds Shortest Paths

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 δ(s,v)\delta(s, v) as the minimum number of edges on any path from ss to vv, or ∞\infty if no path exists. A path from ss to vv of length δ(s,v)\delta(s, v) is a shortest path. The theorem:

When BFS(G,s)(G, s) terminates, v.d=δ(s,v)v.d = \delta(s, v) for every vertex vv. Moreover, for every reachable v≠sv \ne s, a shortest path from ss to vv is a shortest path from ss to v.πv.\pi followed by the edge (v.π,v)(v.\pi, v).

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 (u,v)(u, v), δ(s,v)≤δ(s,u)+1\delta(s, v) \le \delta(s, u) + 1.

If uu is unreachable the right side is ∞\infty. Otherwise a shortest path to uu followed by the edge (u,v)(u, v) is a path to vv with δ(s,u)+1\delta(s, u) + 1 edges, and the shortest path to vv is no longer than that.

Step 2: BFS never underestimates

Lemma 2. At every moment during BFS, v.d≥δ(s,v)v.d \ge \delta(s, v) for every vertex vv.

Induction on the number of ENQUEUE operations. Initially s.d=0=δ(s,s)s.d = 0 = \delta(s, s) and every other v.d=∞v.d = \infty. The only assignment is v.d=u.d+1v.d = u.d + 1 when vv is discovered from uu. By induction u.d≥δ(s,u)u.d \ge \delta(s, u), so v.d=u.d+1≥δ(s,u)+1≥δ(s,v)v.d = u.d + 1 \ge \delta(s, u) + 1 \ge \delta(s, v) by Lemma 1. Since vv is enqueued only once, its dd never changes again.

Step 3: the queue is sorted, with a spread of at most one

Lemma 3. Whenever the queue holds ⟨v1,v2,…,vr⟩\langle v_1, v_2, \ldots, v_r \rangle (head v1v_1, tail vrv_r),

v1.d≤v2.d≤⋯≤vr.dandvr.d≤v1.d+1v_1.d \le v_2.d \le \cdots \le v_r.d \quad \text{and} \quad v_r.d \le v_1.d + 1

Induction on queue operations. With only ss in the queue it is trivial. Dequeue: removing v1v_1 leaves v2v_2 as the head. The chain of inequalities is still sorted, and vr.d≤v1.d+1≤v2.d+1v_r.d \le v_1.d + 1 \le v_2.d + 1. Enqueue: a new vertex vv is discovered from uu, the vertex just dequeued, so v.d=u.d+1v.d = u.d + 1. Before uu left, it was the head, so by induction every queued vertex had d≤u.d+1d \le u.d + 1: the new tail has the largest value, and the sequence stays sorted. The new head v1v_1 was behind uu, so u.d≤v1.du.d \le v_1.d, and v.d=u.d+1≤v1.d+1v.d = u.d + 1 \le v_1.d + 1.

Corollary. If uu is enqueued before vv, then u.d≤v.du.d \le v.d at the moment vv is enqueued. Vertices enter the queue in non-decreasing order of dd, which is the precise form of "waves".

Step 4: the theorem

Suppose some vertex ends with v.d≠δ(s,v)v.d \ne \delta(s, v). Among all such vertices pick one with the smallest δ(s,v)\delta(s, v). By Lemma 2, v.d>δ(s,v)v.d > \delta(s, v), so δ(s,v)\delta(s, v) is finite and v≠sv \ne s. Let uu be the vertex just before vv on a shortest path from ss to vv. Then δ(s,u)=δ(s,v)−1\delta(s, u) = \delta(s, v) - 1, and by the choice of vv, u.d=δ(s,u)u.d = \delta(s, u). So

v.d>δ(s,v)=δ(s,u)+1=u.d+1v.d > \delta(s, v) = \delta(s, u) + 1 = u.d + 1

Now look at the moment BFS dequeues uu, which it does since uu is reachable. Vertex vv is in one of three states. If it is still undiscovered, line 8 sets v.d=u.d+1v.d = u.d + 1: contradiction. If it was already dequeued, it entered the queue before uu, so v.d≤u.dv.d \le u.d by the corollary: contradiction. If it is in the queue, it was discovered from some ww dequeued before uu, so v.d=w.d+1≤u.d+1v.d = w.d + 1 \le u.d + 1: contradiction. Hence v.d=δ(s,v)v.d = \delta(s, v) for all vv. The statement about v.πv.\pi follows because v.d=v.π.d+1v.d = v.\pi.d + 1 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 dd with a brute-force distance: the number of rounds of "extend all known paths by one edge" needed to reach vv.

python · try it yourself
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 CC:

python · try it yourself
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, DD (pushed last) is expanded before BB, its neighbour EE before BB, and EE discovers CC at "distance" 3, although A→B→CA \to B \to C 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 O(V+E)O(V + E): 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?

  1. It never holds more than two vertices
  2. Its dd values are non-decreasing from head to tail and differ by at most 1
  3. It is empty at every level boundary
  4. Every vertex is enqueued twice

Lemma 2 says v.d≥δ(s,v)v.d \ge \delta(s, v) at all times. What does that alone guarantee?

  1. That BFS terminates
  2. That BFS never reports a distance shorter than the true one
  3. That every vertex is reached
  4. That the parent pointers form a tree

In the proof of the theorem, why is vv chosen with the smallest δ(s,v)\delta(s, v) among the wrong vertices?

  1. So that its predecessor uu on a shortest path has a correct dd
  2. So that vv is a leaf
  3. So that vv is the source
  4. So that the queue is empty

BFS is run on a weighted graph, ignoring the weights. What does v.dv.d give?

  1. The least total weight from ss
  2. The fewest edges on a path from ss
  3. The largest weight on any path
  4. Nothing meaningful