TExcelTAD
Home › Graph Algorithms › Why Dijkstra's Algorithm Is Correct

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 GG with non-negative weights and source ss. Then at the moment each vertex uu is extracted from the queue (and added to SS), u.d=δ(s,u)u.d = \delta(s, u). Consequently, u.d=δ(s,u)u.d = \delta(s, u) 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, v.d=δ(s,v)v.d = \delta(s, v) for every v∈Sv \in S.

Initialization. SS is empty.

Maintenance. Suppose, for contradiction, that uu is the first vertex with u.d≠δ(s,u)u.d \ne \delta(s, u) when it is added to SS.

  • u≠su \ne s, because ss is added first with s.d=0=δ(s,s)s.d = 0 = \delta(s, s). So SS is not empty just before uu is added.
  • There must be a path from ss to uu: otherwise δ(s,u)=∞=u.d\delta(s, u) = \infty = u.d by the no-path property. So there is a shortest path pp from ss to uu.
  • Path pp starts in SS (at ss) and ends outside it (at uu). Let yy be the first vertex of pp not in SS, and x∈Sx \in S its predecessor on pp. So pp is s⇝x→y⇝us \leadsto x \to y \leadsto u, where yy may equal uu.
text
        S                         outside S
  s ~~~~~~> x  ------------->  y ~~~~~~~~~~~~> u
            (settled)            (first vertex of p outside S)

Step 1: y.d=δ(s,y)y.d = \delta(s, y). The prefix s⇝x→ys \leadsto x \to y is a shortest path to yy (optimal substructure). When xx was added to SS, x.d=δ(s,x)x.d = \delta(s, x) (by the choice of uu as the first failure), and the edge (x,y)(x, y) was relaxed right then. By the convergence property, y.d=δ(s,y)y.d = \delta(s, y) from that moment on.

Step 2: δ(s,y)≤δ(s,u)\delta(s, y) \le \delta(s, u). Here non-negativity is used: yy comes before uu on the shortest path pp, and the rest of the path, from yy to uu, has weight ≥0\ge 0.

Step 3: combine. Both uu and yy are in QQ when uu is extracted, so u.d≤y.du.d \le y.d. Using the upper-bound property for the last step:

u.d≤y.d=δ(s,y)≤δ(s,u)≤u.du.d \le y.d = \delta(s, y) \le \delta(s, u) \le u.d

All are equal, so u.d=δ(s,u)u.d = \delta(s, u), a contradiction. The invariant holds when uu joins SS.

Termination. The loop ends when QQ is empty, so S=VS = V 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 yy to uu contains a negative edge, δ(s,y)\delta(s, y) can exceed δ(s,u)\delta(s, u), and then uu may be extracted with u.d<y.du.d < y.d even though the true route to uu goes through yy. 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 u.du.d 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.

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

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

  1. y.d=δ(s,y)y.d = \delta(s, y), from the convergence property
  2. δ(s,y)≤δ(s,u)\delta(s, y) \le \delta(s, u), because the path from yy to uu has non-negative weight
  3. u.d≤y.du.d \le y.d, because uu was extracted
  4. The initialization s.d=0s.d = 0

Why does the proof choose yy as the *first* vertex of the shortest path that is outside SS?

  1. So that its predecessor xx is in SS with a correct estimate, and the edge (x,y)(x, y) has already been relaxed
  2. So that y=uy = u
  3. So that yy has the smallest name
  4. So that the path has no negative edges

Does Dijkstra's algorithm remain correct if some edges have weight exactly 0?

  1. Yes: the proof only needs weights ≥0\ge 0
  2. No: zero weights behave like negative weights
  3. Only if the graph is undirected
  4. Only without cycles