Sub topic 11
Why the Greedy Choice Is Correct
Dijkstra's algorithm commits to a vertex's distance the moment it pops that vertex from the heap and never revisits it. That is a strong claim. Breadth-first search makes the same kind of commitment, but only because every edge costs the same. This chapter explains why the commitment is still safe when edge weights differ, provided none is negative.
This chapter assumes you have already read the chapters on edge relaxation, the greedy rule, and the heapq implementation with lazy deletion. It also assumes you are comfortable with proof by contradiction and with the notation δ(s, v) for the true shortest-path distance from the source s to v.
What Exactly Needs Proving
Each vertex has two numbers attached to it during a run:
dist[v]is the tentative distance. It is the cost of the best path to v found so far.- δ(s, v) is the true shortest-path distance. The algorithm never sees it directly.
The algorithm is correct if dist[v] == δ(s, v) for every reachable v when the loop ends. We prove something stronger, which is also more useful:
Greedy invariant. When a vertex u is popped from the heap for the first time (and added to visited), dist[u] = δ(s, u).
Once u is in visited, the algorithm never changes dist[u] in a way that matters, because the popped value is already the true minimum. So the invariant implies correctness. It also explains why early termination works, which the next chapter uses.
Two Supporting Facts
The main argument depends on two smaller facts. Both are easy to prove, and both are easy to forget.
Fact 1: Tentative distances never undershoot
At every moment, dist[v] ≥ δ(s, v).
Every value written into dist[v] comes from dist[u] + w(u, v) for some edge (u, v), and dist[u] itself came from an earlier path. By induction, each tentative distance is the cost of a real walk from s to v. No real walk can be shorter than the shortest path. So relaxation can lower an estimate toward the truth, but it can never push the estimate below it.
Fact 2: Relaxing an edge out of a correct vertex gives its neighbour a correct bound
Suppose dist[x] = δ(s, x) and we relax the edge (x, y). Afterwards:
dist[y] ≤ δ(s, x) + w(x, y)
If some shortest path to y ends with the edge (x, y), the right-hand side equals δ(s, y). Combining this with Fact 1 gives dist[y] = δ(s, y) exactly. This is the "subpath of a shortest path is a shortest path" property, viewed from the relaxation side.
The Proof
We argue by contradiction. Let S be the set of visited vertices at any point in the run.
- Suppose the invariant fails. Let u be the first vertex popped with
dist[u] > δ(s, u). Every vertex popped before u satisfies the invariant. - The source s is popped first with
dist[s] = 0 = δ(s, s), so u ≠ s. Becausedist[u]is finite, u is reachable. Fix a shortest path P from s to u. - At the moment just before u is popped, s is in S and u is not. Walk along P from s. Let y be the first vertex on P that is not in S, and let x be the vertex just before y on P. So x is in S.
- x was popped before u, so by the choice of u,
dist[x] = δ(s, x)when x was popped. At that moment the algorithm relaxed every outgoing edge of x, including (x, y). The part of P from s to y is a shortest path to y, so Fact 2 givesdist[y] = δ(s, y). - y lies on P at or before u, and all edge weights are non-negative. The remaining edges of P from y to u add a total of zero or more, so
δ(s, y) ≤ δ(s, u). - Chain these together:
dist[y] = δ(s, y) ≤ δ(s, u) < dist[u].
- y is not in S, and the relaxation in step 4 pushed the entry
(dist[y], y)onto the heap. That entry is still there, because y has not been popped. The heap is about to pop u with keydist[u], yet it holds an entry with the strictly smaller keydist[y]. A min-heap cannot do that. This is a contradiction.
So no such u exists, and the invariant holds for every popped vertex.
The vertex y may turn out to be u itself. In that case step 4 already gives dist[u] = δ(s, u), which contradicts the assumption directly. The proof covers both cases without change.
Where Non-Negativity Is Used
The proof uses non-negative weights at exactly one point: step 5. With a negative edge somewhere between y and u, δ(s, u) can be smaller than δ(s, y). The chain in step 6 then breaks, and the algorithm can pop u with a key that is still too large. The counterexample in the negative-weights chapter is this situation: C sits outside S with a larger key than B, but the edge C→B has weight −2, so B's true distance is smaller than the value Dijkstra committed to.
Zero-weight edges are fine. Step 5 only needs ≤, not <.
How Lazy Deletion Fits the Proof
The proof talks about "the entry for y in the heap." With lazy deletion, the heap can hold several entries for one vertex, and older ones are stale. Two observations show that this does not matter:
- Every time
dist[y]decreases, a fresh entry(dist[y], y)is pushed. So the heap always contains an entry whose key equals the currentdist[y]. Step 7 needs only that. - Stale entries have keys larger than the current
dist[y]. They can only be popped after the fresh one, and by then y is invisited, so thecontinuethrows them away. A stale entry never becomes the "first pop" of a vertex, and the invariant is a statement about first pops only.
A Consequence: Pop Order Is Monotone
A corollary follows from the proof. The keys of first pops form a non-decreasing sequence. When u is popped with key d, every remaining heap key is at least d. Relaxing u's edges pushes keys of d + w ≥ d. So nothing smaller can appear later.
This is the weighted version of BFS's "layer by layer" order. Dijkstra settles vertices in order of true distance, like a wavefront moving outward. The next chapter uses this to stop early. Once the target is popped, every vertex still waiting is at least as far away, so none of them can lead to a shorter route.
| Property | Holds with non-negative weights | Holds with a negative edge |
|---|---|---|
| `dist[v] ≥ δ(s, v)` at all times | Yes | Yes (if no negative cycle) |
| First pop of u has `dist[u] = δ(s, u)` | Yes | No |
| First-pop keys are non-decreasing | Yes | No |
| Stopping at the target's pop is safe | Yes | No |
Checking the Invariant Empirically
A proof is the real guarantee. Still, a randomized check catches implementation bugs that the proof cannot, such as a misplaced visited.add or comparing against the wrong key. The script below instruments the heap-based algorithm and checks each first pop against Bellman-Ford on 2,000 random graphs.
import heapq
import random
def dijkstra_checked(graph, source):
"""Heap-based Dijkstra that also records (vertex, key) at each first pop."""
dist = {source: 0}
heap = [(0, source)]
visited = set()
pop_order = []
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
pop_order.append((u, d))
for v, w in graph.get(u, []):
nd = d + w
if v not in dist or nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
return dist, pop_order
def bellman_ford(graph, source):
"""Reference shortest distances; assumes no negative cycles."""
nodes = set(graph) | {v for edges in graph.values() for v, _ in edges}
dist = {source: 0}
for _ in range(len(nodes) - 1):
changed = False
for u, edges in graph.items():
if u not in dist:
continue
for v, w in edges:
if v not in dist or dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
break
return dist
def random_graph(n, m, max_w, rng):
graph = {i: [] for i in range(n)}
for _ in range(m):
u, v = rng.randrange(n), rng.randrange(n)
graph[u].append((v, rng.randint(0, max_w)))
return graph
rng = random.Random(42)
for _ in range(2000):
g = random_graph(8, 20, 10, rng)
dist, order = dijkstra_checked(g, 0)
truth = bellman_ford(g, 0)
assert dist == truth, (g, dist, truth)
# Greedy invariant: each first pop carries the true distance.
assert all(truth[u] == d for u, d in order)
# Corollary: first-pop keys never decrease.
keys = [d for _, d in order]
assert keys == sorted(keys)
print("invariant held on 2000 random graphs")The weights are drawn from 0 to 10, so zero-weight edges and self-loops are included on purpose. Both are legal, and both are places where a careless implementation can go wrong.
Exercises
Exercise
In step 1 of the proof, why must u be the first vertex popped with a wrong distance, rather than any such vertex?
Show answer
Step 4 needs x, which was popped before u, to have a correct distance so that relaxing (x, y) gives y a correct bound. Choosing u as the first failure guarantees that every earlier pop, including x, satisfies the invariant. If u were an arbitrary failure, x might be wrong too and the argument would stall.
Exercise
Change rng.randint(0, max_w) to rng.randint(-3, max_w) in the checker and run it. Which assertion fails first, and which step of the proof no longer holds? (Bellman-Ford's answer is also unreliable if a random graph contains a negative cycle. Explain why the failure you see does not depend on that.)
Show answer
The distance comparison or the "first pop carries the true distance" assertion fails, usually within the first few trials. Step 5 breaks: with a negative edge after y on the path, δ(s, y) can exceed δ(s, u), so the heap may correctly pop u before y while dist[u] is still too large. Graphs with negative edges but no negative cycle are enough to trigger the failure, as in the A→C→B→D counterexample, so the result does not rely on Bellman-Ford handling cycles.
Exercise
A colleague suggests skipping the visited check and instead skipping a popped entry only when d > dist[u]. Does the greedy invariant still hold for the first time each vertex is processed?
Show answer
Yes. The first entry popped for u has key equal to the current dist[u]. Any later entry either has d > dist[u] and is skipped, or, if keys tie, has d == dist[u] and reprocesses u harmlessly. The proof only concerns the first pop, and its key is still the minimum, so the invariant holds. Ties can cause duplicate relaxation work, but no wrong distances.
Exercise
Using the monotone pop-order corollary, explain why the moment the target t is popped, no vertex still in the heap can lie on a shorter path to t.
Show answer
Every remaining heap key is at least dist[t] = δ(s, t), and each such key is at least the true distance of its vertex. Any path to t through a remaining vertex z costs at least δ(s, z) plus non-negative edge weights, which is at least dist[t]. So no unpopped vertex can produce a cheaper route, and returning at t's pop is safe.