4112553ACSBDnext out1dist[s] = 02pq = [(0, s)]3while pq:4 d, u = heappop(pq)5 if d > dist[u]: continue6 for v, w in graph[u]:7 if d + w < dist[v]:8 dist[v] = d + w9 heappush(pq, (d + w, v))SABCDdist(0,S)(4,A)(1,B)(3,A)(6,C)(6,D)(4,C)(7,D)
Blocks: offers (cost, vertex), in the queue smallest firstRoads: one-way edges with their weightsYellow ring: a settled vertex, its cost is finalDijkstra's algorithm on a directed graph with non-negative weights, run by the Python loop on the card. Each block is an offer (cost, vertex): it slides along a road when the road is relaxed, joins the priority queue if it beats dist, and leaves the queue smallest first. A yellow ring marks a settled vertex, whose cost is final; an offer that comes out after its vertex is settled is stale and skipped.

The problem

  1. 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.

Running Dijkstra

Results and proof

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.