Why Dijkstra's Algorithm Is Correct
Dijkstra's algorithm is greedy: the moment a vertex has the smallest estimate among the unsettled ones, it declares that estimate final and never looks at it again. Greedy algorithms need proofs, and this one has a short, classic proof whose one essential step uses the assumption that no edge weight is negative. This lesson gives the proof, shows exactly where non-negativity enters, and tests the theorem on random graphs and on a grid.
The theorem
Theorem. Run DIJKSTRA on a weighted directed graph with non-negative weights and source . Then at the moment each vertex is extracted from the queue (and added to ), . Consequently, for all vertices at termination, and the predecessor edges form a shortest-path tree.
The proof uses the loop invariant: at the start of each iteration of the while loop, for every .
Initialization. is empty.
Maintenance. Suppose, for contradiction, that is the first vertex with when it is added to .
- , because is added first with . So is not empty just before is added.
- There must be a path from to : otherwise by the no-path property. So there is a shortest path from to .
- Path starts in (at ) and ends outside it (at ). Let be the first vertex of not in , and its predecessor on . So is , where may equal .
S outside S
s ~~~~~~> x -------------> y ~~~~~~~~~~~~> u
(settled) (first vertex of p outside S)Step 1: . The prefix is a shortest path to (optimal substructure). When was added to , (by the choice of as the first failure), and the edge was relaxed right then. By the convergence property, from that moment on.
Step 2: . Here non-negativity is used: comes before on the shortest path , and the rest of the path, from to , has weight .
Step 3: combine. Both and are in when is extracted, so . Using the upper-bound property for the last step:
All are equal, so , a contradiction. The invariant holds when joins .
Termination. The loop ends when is empty, so and every estimate is a shortest-path distance. The predecessor-subgraph property makes the parent edges a shortest-path tree.
Where the proof fails with a negative edge. Only Step 2 used the signs. If the segment from to contains a negative edge, can exceed , and then may be extracted with even though the true route to goes through . That is exactly the counterexample of the previous lesson.
Testing the theorem
The program runs Dijkstra on 500 random directed graphs with non-negative integer weights, including zeros. At every extraction it compares with the true distance from Bellman-Ford, and it checks that the extracted values never decrease. Then it repeats the experiment with some negative weights (but no negative cycles) and counts how often Dijkstra goes wrong.
import heapq, random
INF = float("inf")
def bellman_ford(n, edges, s):
d = [INF] * n; d[s] = 0
for _ in range(n - 1):
for u, v, w in edges:
if d[u] + w < d[v]:
d[v] = d[u] + w
return d
def dijkstra_checked(n, edges, s, delta):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
d, done, pq = [INF] * n, [False] * n, [(0, s)]
d[s] = 0
last, wrong_at_extraction, monotone = -INF, 0, True
while pq:
du, u = heapq.heappop(pq)
if done[u]:
continue
done[u] = True
wrong_at_extraction += du != delta[u]
monotone &= du >= last
last = du
for v, w in adj[u]:
if not done[v] and du + w < d[v]:
d[v] = du + w
heapq.heappush(pq, (d[v], v))
return d, wrong_at_extraction, monotone
def random_graph(rng, n, negative):
h = [rng.randint(0, 8) for _ in range(n)] # potentials keep every cycle non-negative
edges = []
for u in range(n):
for v in range(n):
if u != v and rng.random() < 0.25:
w = rng.randint(0, 9)
edges.append((u, v, w + (h[u] - h[v] if negative else 0)))
return edges
rng = random.Random(10)
for negative in (False, True):
failures = extractions_wrong = 0
all_monotone = True
for trial in range(500):
n = rng.randint(2, 12)
edges = random_graph(rng, n, negative)
delta = bellman_ford(n, edges, 0)
d, wrong, mono = dijkstra_checked(n, edges, 0, delta)
failures += d != delta
extractions_wrong += wrong
all_monotone &= mono
label = "with negative edges " if negative else "non-negative weights "
print(f"{label}: {failures:3} of 500 graphs wrong, {extractions_wrong:3} wrong extractions, "
f"extracted values never decrease: {all_monotone}")non-negative weights : 0 of 500 graphs wrong, 0 wrong extractions, extracted values never decrease: True
with negative edges : 36 of 500 graphs wrong, 73 wrong extractions, extracted values never decrease: False
With non-negative weights every extraction is exact and the extracted distances never decrease: the "waves" of BFS, now measured in weight. With negative edges a noticeable share of graphs come out wrong, and the extracted values can even go down, since a negative edge can lead from a settled vertex to one with a smaller distance.
Wavefronts on a grid
On a grid where each move costs the weight of the cell it enters, the settled region grows like an expanding wave whose speed depends on the terrain. The animation uses cost 1 for open cells and 3 for the slow cells marked ~; ties are broken by discovery order.
The Python version is the same algorithm on the same grid, with neighbours in the order up, right, down, left and ties broken by discovery order (the seq counter in each heap entry). It stops when the goal is settled.
import heapq
grid = ["S...#....", "..~.#.##.", ".~~...#..", "..~.#.#.G", "....#...."]
rows, cols = len(grid), len(grid[0])
find = lambda ch: next((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == ch)
S, G = find("S"), find("G")
cost = lambda r, c: 3 if grid[r][c] == "~" else 1
g = {S: 0}
prev = {}
closed = []
seq = 0
pq = [(0, seq, S)]
while pq:
gc, _, cell = heapq.heappop(pq)
if cell in closed:
continue
closed.append(cell)
if cell == G:
break
r, c = cell
for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#" and (nr, nc) not in closed:
ng = gc + cost(nr, nc)
if (nr, nc) not in g or ng < g[(nr, nc)]:
g[(nr, nc)] = ng
prev[(nr, nc)] = cell
seq += 1
heapq.heappush(pq, (ng, seq, (nr, nc)))
path = [G]
while path[-1] != S:
path.append(prev[path[-1]])
print(f"path found: {len(path) - 1} moves, cost {g[G]}, {len(closed)} cells expanded")
rows_out = [list(row) for row in grid]
for r, c in path[1:-1]:
rows_out[r][c] = "*"
print("\n".join("".join(row) for row in rows_out))
print("costs settled in order:", [g[cell] for cell in closed])path found: 13 moves, cost 13, 36 cells expanded
S***#....
..~*#.##.
.~~***#..
..~.#*#*G
....#***.
costs settled in order: [0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13]
The settled costs form a non-decreasing sequence, the theorem's monotonicity in action. The route never enters a slow cell: 13 moves at cost 1 each, two more than the Manhattan distance of 11, because the walls force detours.
Test yourself
In the correctness proof, which step uses the assumption that weights are non-negative?
- , from the convergence property
- , because the path from to has non-negative weight
- , because was extracted
- The initialization
Why does the proof choose as the *first* vertex of the shortest path that is outside ?
- So that its predecessor is in with a correct estimate, and the edge has already been relaxed
- So that
- So that has the smallest name
- So that the path has no negative edges
Does Dijkstra's algorithm remain correct if some edges have weight exactly 0?
- Yes: the proof only needs weights
- No: zero weights behave like negative weights
- Only if the graph is undirected
- Only without cycles