The problem
Five places joined by one-way roads. Each road has a cost, its weight, and no weight is negative. Question: what is the cheapest route from S to every other vertex? Adding up costs along a route gives its length.
dist holds the best cost found so far. Every vertex starts at infinity (∞, no route known yet) and S at 0. A priority queue (a min-heap) holds offers (cost, vertex) and always hands out the smallest. It starts with (0, S).
Running Dijkstra
Pop the smallest offer, (0, S). Relax each road out of S: is 0 + weight cheaper than dist? A: 0 + 4 = 4 < ∞, so write 4 and push (4, A). B: 0 + 1 = 1, push (1, B).
The smallest offer is (1, B), so B is settled at 1. Through B, A costs 1 + 2 = 3, cheaper than 4: dist[A] becomes 3 and (3, A) is pushed. C and D get 6 each.
Next comes (3, A). Its road to C costs 3 + 1 = 4, which beats 6. So dist[C] becomes 4 and (4, C) joins the queue. The route S, B, A, C is now the best known way to C.
Out comes (4, A), the old offer. A already costs 3, and 4 > 3, so line 5 skips it. Python’s heapq cannot lower an entry in place, so we push a new one and ignore stale ones. This is called lazy deletion.
Pop (4, C): C settles at 4. Its road to D offers 4 + 3 = 7. But dist[D] is already 6, and 7 is not less than 6, so nothing changes. The offer is dropped and never enters the queue.
(6, C) is stale, so it is skipped. (6, D) settles D at 6; D has no roads out. The queue is now empty, so the while loop ends. Every vertex holds its cheapest cost.
Results and proof
Each final cost was set by one road; those roads form a tree. The cheapest way to C is S, B, A, C: 1 + 2 + 1 = 4, beating S, A, C at 5. Store each previous vertex to rebuild routes.
When B left the queue at 1, every other route to B had to leave S through a vertex still in the queue, like A at 4 or more. Weights are never negative, so going on can only add. Nothing beats 1.
Each road is relaxed once, so there are at most E + 1 pushes and pops. Each takes O(log V) on a binary heap. Total: O((V + E) log V). Here: 7 relaxations, 7 pushes, 7 pops.
What happens
;; step 1/11 · the-graph a weighted directed graph, V = 5 vertices, E = 7 edges S → A weight 4 S → B weight 1 A → C weight 1 B → A weight 2 B → C weight 5 B → D weight 5 C → D weight 3 every weight ≥ 0 (Dijkstra needs this) goal: dist[v] = length of the cheapest route S → v
The figure lines the queue up smallest first so it is easy to read. Python’s heapq really keeps the list in heap order, where only pq[0] is guaranteed to be the smallest; heappop returns the same offers in the same order. Textbook versions (MIT 6.006, CLRS, Sedgewick and Wayne’s IndexMinPQ) use a decrease-key operation instead of stale entries, so the queue holds at most V items. The lazy version used here is the one the Python heapq documentation suggests; it has the same O((V + E) log V) bound.