Sub topic 13
Dijkstra's Algorithm as a Greedy Algorithm
This chapter assumes you know Python, binary heaps through heapq, adjacency lists, and the greedy-stays-ahead proof style from earlier in the tutorial. It covers single-source shortest paths: given a weighted directed graph and a source vertex s, find the length of the shortest path from s to every vertex it can reach.
Dijkstra's algorithm is usually taught as a graph algorithm. It is also a greedy algorithm. At each step it makes one irrevocable choice: it declares the closest unsettled vertex finished. This chapter shows why that choice is safe, where the proof depends on non-negative weights, and what goes wrong when the weights are negative.
The Greedy Choice
The algorithm keeps a tentative distance dist[v] for each vertex it has seen. It also keeps a set S of settled vertices, whose distances are final. The loop has three steps:
- Pick the unsettled vertex
uwith the smallest tentative distance. - Settle
u. Its distance never changes again. - Relax every edge
(u, v, w): ifdist[u] + w < dist[v], lowerdist[v].
Step 1 is the greedy choice. The algorithm does not look ahead and does not reconsider. Among all remaining vertices it commits to the one that currently looks closest.
Implementation
Python's heapq has no decrease-key operation. The standard workaround is lazy deletion. When a distance improves, push a new entry, and when you pop an entry, skip it if it is stale, meaning it is larger than the best known distance.
import heapq
def dijkstra(graph, source):
dist = {source: 0}
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist.get(u, float("inf")):
continue
for v, w in graph.get(u, []):
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
heapq.heappush(heap, (nd, v))
return dist
graph = {"A": [("B", 1), ("C", 4)], "B": [("C", 2), ("D", 5)], "C": [("D", 1)]}
print(dijkstra(graph, "A")) # {'A': 0, 'B': 1, 'C': 3, 'D': 4}The settled set is implicit here. A vertex is settled the first time a non-stale entry for it is popped. Vertices that cannot be reached from the source never appear in dist. Code that calls this function must treat a missing key as infinity.
Trace
| Step | Popped | Action | dist after step |
|---|---|---|---|
| 1 | (0, A) | settle A; B=1, C=4 | A0 B1 C4 |
| 2 | (1, B) | settle B; C=3, D=6 | A0 B1 C3 D6 |
| 3 | (3, C) | settle C; D=4 | A0 B1 C3 D4 |
| 4 | (4, C) | stale, skip | unchanged |
| 5 | (4, D) | settle D | unchanged |
| 6 | (6, D) | stale, skip | unchanged |
The tentative distances for C and D each dropped once before the vertex was settled. Each drop left a stale entry in the heap, and both were discarded.
Recovering the Paths
Distances alone are often not enough. Record a predecessor whenever a relaxation succeeds, then walk the predecessors backward from the target:
import heapq
def dijkstra_with_paths(graph, source):
dist = {source: 0}
prev = {source: None}
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue
for v, w in graph.get(u, []):
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
prev[v] = u
heapq.heappush(heap, (nd, v))
return dist, prev
def path_to(prev, target):
if target not in prev:
return None
path = []
while target is not None:
path.append(target)
target = prev[target]
return path[::-1]
graph = {"A": [("B", 1), ("C", 4)], "B": [("C", 2), ("D", 5)], "C": [("D", 1)]}
dist, prev = dijkstra_with_paths(graph, "A")
print(dist["D"], path_to(prev, "D")) # 4 ['A', 'B', 'C', 'D']Why the Greedy Choice Is Safe
Let δ(v) be the true shortest-path distance from s to v. The claim is a greedy-stays-ahead invariant:
Invariant. When a vertex u is settled, dist[u] = δ(u).
Relaxation only ever sets dist[v] to the length of a real path, so dist[v] ≥ δ(v) always holds. It remains to show that dist[u] ≤ δ(u) at the moment u is settled.
Proof by induction on the number of settled vertices. The source is settled first with dist[s] = 0 = δ(s). Now suppose every vertex in S was settled correctly, and u is the next vertex chosen. Take a shortest path P from s to u. P starts inside S and ends outside it, so it has a first edge (x, y) with x in S and y not in S.
xwas settled correctly, and its edges were relaxed when it was settled. Sodist[y] ≤ δ(x) + w(x, y) = δ(y). The equality holds because a prefix of a shortest path is itself a shortest path.- The rest of
P, fromytou, has non-negative length, soδ(y) ≤ δ(u). - The algorithm chose
uovery, sodist[u] ≤ dist[y].
Chaining these gives dist[u] ≤ dist[y] ≤ δ(y) ≤ δ(u). Combined with dist[u] ≥ δ(u), this proves dist[u] = δ(u).
The argument has the stays-ahead shape. No algorithm can reach any vertex outside S more cheaply than the greedy frontier allows, so the closest frontier vertex is already optimal.
Failure With Negative Weights
To see the failure directly, use a version that tracks the settled set explicitly and refuses to update settled vertices, as the greedy invariant permits:
import heapq
def dijkstra_settled(graph, source):
dist = {source: 0}
done = set()
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if u in done:
continue
done.add(u)
for v, w in graph.get(u, []):
if v in done:
continue
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
heapq.heappush(heap, (nd, v))
return dist
graph = {"A": [("B", 2), ("C", 3)], "C": [("B", -2)]}
print(dijkstra_settled(graph, "A")) # {'A': 0, 'B': 2, 'C': 3}, but the true distance to B is 1The algorithm settles B at distance 2 before it looks at C. The path A→C→B has length 1, and it is found too late.
The lazy-deletion version above does not have a done check. It would re-push B and happen to get this case right. Don't rely on that. With negative edges, that version can re-settle vertices exponentially many times. With a negative cycle, it never terminates. For negative weights, use Bellman-Ford, which runs in O(VE) and detects negative cycles.
Complexity
| Priority queue | Time | Best for |
|---|---|---|
| Unsorted array | O(V²) | Dense graphs, E close to V² |
| Binary heap, lazy deletion | O((V + E) log V) | Sparse graphs; the practical default |
| Fibonacci heap | O(E + V log V) | Mostly theoretical |
With lazy deletion the heap can hold up to E entries, so each operation costs O(log E). Since E ≤ V², log E ≤ 2 log V, and the bound is still O((V + E) log V).
Relationship to Prim's Algorithm
Prim's algorithm for minimum spanning trees has the same structure: grow a set from a start vertex and repeatedly add the cheapest frontier vertex. The two algorithms differ only in the key they store for each vertex.
| Row | Dijkstra | Prim |
|---|---|---|
| Key of frontier vertex v | `dist[u] + w(u, v)`, the total path length | `w(u, v)`, a single edge weight |
| Correctness argument | Greedy stays ahead | Cut property (exchange) |
| Negative weights | Breaks | Fine |
Because Prim's key is one edge weight rather than an accumulated sum, negative edges don't affect it. The cut property only compares edge weights against each other.
Common Errors
- Marking vertices visited on push instead of pop. A vertex's first tentative distance is not always its best one. In the trace above, C was first reached at 4 and settled at 3.
- Leaving out the stale check. The results are still correct, because relaxing from a stale entry can never improve anything. But every stale entry re-scans its vertex's edges, which wastes work.
- Heap entries that cannot be compared. If two entries share a distance, Python compares the second elements. Vertex objects without an ordering raise
TypeError. Add a counter as a tiebreaker, as in the Huffman chapter. - Stopping too early for a single target. You may stop when the target is popped and not stale. Stopping when it is first pushed is wrong.
- Ignoring unreachable vertices. Use
dist.get(v, float("inf"))instead ofdist[v].
Exercise
In the correctness proof, identify the inequality that fails for the graph {"A": [("B", 2), ("C", 3)], "C": [("B", -2)]} when B is settled.
Show answer
When B is settled, S = {A}. The shortest path to B is A→C→B, and its first edge leaving S is (A, C), so y = C. The proof needs δ(y) ≤ δ(u), which here is δ(C) = 3 ≤ δ(B) = 1. That is false because the remaining edge C→B has negative weight.
Exercise
Show that adding 2 to every edge of the graph with edges A→C weight 1, A→B weight 2 and B→C weight −2 changes the shortest path from A to C.
Show answer
In the original graph, the path A→B→C has length 0 and the direct edge A→C has length 1, so A→B→C is shortest. After adding 2 to every edge, A→B→C has length 4 + 0 = 4 and A→C has length 3, so the direct edge becomes shortest. The two-edge path was penalized twice.
Exercise
Modify dijkstra so that it returns as soon as the shortest distance to a given target is known. Where exactly does the early exit go, and why is it correct there?
Show answer
Put the check immediately after the stale check: if u == target: return d. When a non-stale entry for u is popped, u is being settled, and the invariant guarantees that d = δ(u). Checking when the target is pushed or relaxed would be wrong, because a later relaxation could still lower its distance.