Sub topic 13
Dijkstra's Algorithm as a Greedy Algorithm
This chapter assumes you know graph basics (vertices, weighted edges, adjacency lists), Python's heapq priority queue, and the greedy-stays-ahead proof technique from an earlier chapter.
Dijkstra's algorithm finds the shortest distance from one source vertex to every other vertex. It is greedy because at every step it takes the unsettled vertex with the smallest tentative distance and declares that distance final. It never revisits that decision.
The Working Model
The algorithm keeps two pieces of state:
dist: the best distance found so far for each discovered vertex.done: the settled vertices, whose distances are final.
Each round, the algorithm pops the closest vertex from a min-heap, settles it, and relaxes its outgoing edges. To relax an edge (u, v, w) means to check whether going through u gives v a shorter distance, and to update dist[v] if it does.
The code below marks the greedy decision explicitly with a done set:
import heapq
def dijkstra(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) # greedy choice: dist[u] is now final
for v, w in graph.get(u, []):
nd = d + w
if v not in done and 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 heap can hold stale entries, such as (4, "C") after C improves to 3. The if u in done check skips them. This technique is called lazy deletion. With a binary heap the algorithm runs in O((V + E) log V) time.
Why the Greedy Choice Is Safe: Greedy Stays Ahead
The invariant is that when u is popped for the first time, dist[u] equals the true shortest distance to u.
Suppose some shorter path P to u exists. P starts inside the settled set and must leave it at some first edge (x, y), with x settled and y not. When x was settled, relaxing that edge set dist[y] to at most dist[x] + w(x, y), which is the length of P up to y. If all weights are non-negative, the rest of P cannot make it shorter, so dist[y] ≤ length(P) < dist[u]. Then the heap would have popped y before u. That contradicts the choice of u, so no shorter path exists.
Common Error: Negative Edge Weights
The proof needs the step "a prefix of a path is no longer than the whole path." A negative edge breaks that step.
neg = {"A": [("B", 2), ("C", 3)], "C": [("B", -2)]}
print(dijkstra(neg, "A")) # {'A': 0, 'B': 2, 'C': 3}, but the true distance to B is 1B is settled at distance 2 before the route A → C → B of length 1 is seen. Use Bellman–Ford when the graph has negative weights.
Exercise
A colleague proposes handling negative weights by adding a constant to every edge so that all weights become non-negative, then running Dijkstra. Does this work? Test it on the neg graph above.
Show answer
No. Adding 2 to every edge gives A→B = 4, A→C = 5, C→B = 0. Dijkstra now picks A→B (4) over A→C→B (5), which corresponds to length 2 in the original graph, while the true shortest path is A→C→B with length 1. The shift adds the constant once per edge, so it penalizes paths with more edges and changes which path is shortest.