Sub topic 10
Prim's Algorithm: Growing a Single Tree from a Start Vertex
This chapter assumes you already know the cut property, the generic greedy MST strategy, and how a binary-heap priority queue works. It also uses Python's heapq module and the adjacency-list representation from earlier chapters.
Kruskal's algorithm builds several small trees and merges them. Prim's algorithm grows exactly one tree. It begins at a start vertex. At each step it adds the lightest edge that joins a tree vertex to a non-tree vertex.
Why Prim's Choice Is Safe
At any moment, the vertices already in the tree form one side of a cut, and every other vertex forms the other side. Prim's algorithm takes the lightest edge that crosses this cut. The cut property says that edge belongs to some MST. Each step therefore keeps the partial tree inside some minimum spanning tree, and after V − 1 additions the tree is a complete MST.
The Working Model
The heap holds candidate edges as (weight, vertex, parent) tuples. This version is called lazy Prim because it never updates or removes entries in the heap. Old entries stay in the heap and get skipped when they are popped.
Implementation
import heapq
def prim(adj, start=0):
# adj: list where adj[v] is a list of (neighbor, weight) pairs
n = len(adj)
visited = [False] * n
heap = [(0, start, -1)] # (edge weight, vertex, parent)
total = 0
mst = []
while heap:
w, v, parent = heapq.heappop(heap)
if visited[v]:
continue # stale entry; v was already reached by a lighter edge
visited[v] = True
total += w
if parent != -1:
mst.append((parent, v, w))
for u, wu in adj[v]:
if not visited[u]:
heapq.heappush(heap, (wu, u, v))
return total, mst
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
n = 4
adj = [[] for _ in range(n)]
for w, u, v in edges:
adj[u].append((v, w))
adj[v].append((u, w))
print(prim(adj)) # (6, [(0, 1, 1), (1, 3, 2), (1, 2, 3)])Tracing It by Hand
Here is the trace on the four-vertex graph above, starting from vertex 0:
| Step | Popped | Action | Heap afterwards |
|---|---|---|---|
| 1 | (0, 0, −1) | Visit 0 | (1,1,0), (4,2,0) |
| 2 | (1, 1, 0) | Add 0–1 (w 1) | (2,3,1), (3,2,1), (4,2,0) |
| 3 | (2, 3, 1) | Add 1–3 (w 2) | (3,2,1), (4,2,0), (5,2,3) |
| 4 | (3, 2, 1) | Add 1–2 (w 3) | (4,2,0), (5,2,3) |
| 5 | (4, 2, 0) | Stale, skip | (5,2,3) |
| 6 | (5, 2, 3) | Stale, skip | empty |
The total is 1 + 2 + 3 = 6. Vertex 2 had three entries in the heap at once. Only the lightest one was used.
Common Errors
- Marking vertices visited at push time. Vertex 2 would then be locked in through the weight-4 edge, and the weight-3 edge would never be used. Mark a vertex visited when you pop it.
- Dropping the stale-entry check. Without
continue, a vertex is processed more than once, and the code adds duplicate edges and too much weight. - Assuming the whole graph is covered. Prim's algorithm only reaches the start vertex's component. If
len(mst) < n - 1, the graph is disconnected. A later chapter covers spanning forests. - Wrong heap order. Weight has to be the first tuple field, because
heapqcompares tuples from left to right.
Exercise
Run prim(adj, start=3) on the example graph. In what order are the edges added, and what is the total weight?
Show answer
Starting at 3, the heap holds (2,1,3) and (5,2,3). Pop (2,1,3) and add 3–1. Vertex 1 pushes (1,0,1) and (3,2,1). Pop (1,0,1) and add 1–0. Vertex 0 pushes (4,2,0). Pop (3,2,1) and add 1–2. The result is [(3,1,2), (1,0,1), (1,2,3)] with total 6. The edge set is the same as before; only the order changed.
Exercise
Why is it wrong to skip pushing (u, wu) when u already has an entry in the heap?
Show answer
The new edge may be lighter than the existing entry. Lazy Prim's algorithm depends on the heap holding every candidate edge, so the lightest one reaches the top first. Skipping it could put a heavier edge in the tree.