1seen, tree = set(), []2pq = [(0, s, s)]3while pq:4 w, u, v = heappop(pq)5 if v in seen: continue6 seen.add(v)7 if u != v: tree.append((u, v, w))8 for x, wx in graph[v]:9 if x not in seen:10 heappush(pq, (wx, v, x))4125763BADCEpq[0]tree edges0total weight00 A4 A-B1 A-C2 C-B7 C-D6 C-E5 B-D3 D-E
Discs: vertices; a yellow ring means the vertex is in the treeCables: edges with their weights; a yellow band means the edge is in the treeMoving tiles: offers (weight, from, to) in the priority queueLazy Prim on a five-vertex graph: offers (weight, from, to) slide from the cables into a min-priority queue, and the smallest always leaves first. A new vertex joins with a yellow ring and its cable is laid with a yellow band; an offer whose ends are both in the tree is stale and fades. The tree ends as A–C, C–B, B–D and D–E, total weight 11.

The problem

  1. Five places and seven possible cables, each with a cost: its weight. A spanning tree joins every vertex using V − 1 = 4 edges and no cycle. The minimum spanning tree (MST) is the one with the smallest total weight.

Growing the tree

Proof and cost

What happens

;; step 1/11 · the-problem
an undirected weighted graph, V = 5 vertices, E = 7 edges
  A – B   weight 4
  A – C   weight 1
  B – C   weight 2
  B – D   weight 5
  C – D   weight 7
  C – E   weight 6
  D – E   weight 3

spanning tree: V − 1 edges, reaches every vertex, no cycle
all weights differ, so exactly one MST exists

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 hands out the same offers in the same order. This is lazy Prim: stale offers stay in the queue (Sedgewick and Wayne: space proportional to E, time proportional to E log E). The eager version keeps one offer per vertex in an indexed queue and lowers it with decrease-key: space V, time E log V. CLRS and MIT 6.046J use that version.