Sub topic 10
Prim's Algorithm: Growing a Single Tree from a Start Vertex
This chapter assumes you already know the cut property, which says the lightest edge crossing any cut is safe to add to a minimum spanning tree. It also assumes you know how a binary-heap priority queue supports push and pop-min in O(log n) time, and that you can read Python adjacency lists. Kruskal's algorithm builds a forest of many small trees and merges them. Prim's algorithm keeps exactly one tree from start to finish. It begins at a single vertex and adds one vertex per step, each time through the cheapest edge that reaches outside the tree.
The Working Model
At every moment, Prim's algorithm splits the vertices into two groups:
- Visited: vertices already in the tree.
- Unvisited: everything else.
That split is a cut. The edges with one end in each group are the crossing edges. Prim's algorithm picks the lightest crossing edge, adds it to the tree, and moves its unvisited endpoint into the visited group. The cut property guarantees that edge belongs to some MST, so each step is safe. After V − 1 additions on a connected graph, every vertex is visited and the tree is a minimum spanning tree.
The only real engineering question is how to find the lightest crossing edge quickly. A linear scan over all edges at every step costs O(V · E). A priority queue brings this down to O(E log V).
The Implementation
The version below is called lazy Prim's. It never removes outdated entries from the heap. When an entry's vertex has already been visited, the algorithm skips it at pop time.
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)])Each heap entry is a tuple (weight, vertex, parent). Python compares tuples left to right, so heapq orders entries by weight first. Ties fall back to the vertex number, which is an integer, so comparison never fails. The parent field exists only so the algorithm can report which edge brought v into the tree. The start vertex gets the fake parent -1 and weight 0, so it adds nothing to the total.
Why the popped edge is the lightest crossing edge
When a vertex x becomes visited, the loop pushes every edge from x to an unvisited neighbor. So every crossing edge in the current cut sits in the heap, because its visited endpoint pushed it. The heap can also hold entries whose target has since been visited. Those edges no longer cross the cut, and the visited[v] check throws them away. The first non-stale entry popped is therefore the minimum-weight crossing edge, which is exactly what the cut property needs.
Tracing by Hand
Here is the four-vertex example graph used throughout this tutorial.
The trace below starts at vertex 0. The heap column shows the contents after the step, sorted by weight for readability. The real heap is only partially ordered.
| Step | Popped | Action | Visited | Heap after step | Total |
|---|---|---|---|---|---|
| 0 | none | push start | {} | (0,0,−1) | 0 |
| 1 | (0,0,−1) | visit 0, push edges to 1 and 2 | {0} | (1,1,0), (4,2,0) | 0 |
| 2 | (1,1,0) | visit 1, record 0–1, push to 2 and 3 | {0,1} | (2,3,1), (3,2,1), (4,2,0) | 1 |
| 3 | (2,3,1) | visit 3, record 1–3, push to 2 | {0,1,3} | (3,2,1), (4,2,0), (5,2,3) | 3 |
| 4 | (3,2,1) | visit 2, record 1–2, no unvisited neighbors | {0,1,2,3} | (4,2,0), (5,2,3) | 6 |
| 5 | (4,2,0) | stale, skip | same | (5,2,3) | 6 |
| 6 | (5,2,3) | stale, skip | same | empty | 6 |
Vertex 2 appears in the heap three times, through edges of weight 3, 4, and 5. Only the lightest one counts. The other two are the stale entries the visited check exists for. The result matches Kruskal's: total weight 6, using edges 0–1, 1–3, and 1–2.
Lazy Versus Eager Prim's
The lazy version can push one entry per edge direction, so the heap can grow to O(E) entries. Each push and pop costs O(log E). Because E ≤ V², log E ≤ 2 log V, so the total is O(E log V).
An eager variant keeps at most one heap entry per vertex. That entry holds the best known edge into the vertex. When a lighter edge turns up, the algorithm runs a decrease-key operation instead of pushing a duplicate. This caps the heap at V entries and saves memory on dense graphs. Python's heapq has no decrease-key, though, and working around that (an indexed heap, or lazy deletion anyway) adds complexity without improving the O(E log V) bound. With a Fibonacci heap, the eager version reaches O(E + V log V). The chapter on running time compares these options against Kruskal's.
| Variant | Heap size | Time | Needs decrease-key |
|---|---|---|---|
| Lazy, binary heap | O(E) | O(E log V) | No |
| Eager, indexed binary heap | O(V) | O(E log V) | Yes |
| Eager, Fibonacci heap | O(V) | O(E + V log V) | Yes |
| Array scan, no heap | none | O(V²) | No |
The array-scan version keeps a best[v] array and scans it in O(V) to find the next vertex. On a dense graph where E ≈ V², O(V²) beats O(E log V).
Common Errors
Marking vertices visited at push time
It is tempting to set visited[u] = True when you push u, to keep duplicates out of the heap. This is wrong. The first edge pushed toward u is not necessarily the lightest one. In the trace above, vertex 2 is first pushed with weight 4 from vertex 0. If it were marked visited then, the cheaper weight-3 edge from vertex 1 would be ignored, and the total would come out as 7.
Removing the stale-entry check
If you delete the if visited[v]: continue line, stale entries get processed as new tree edges. The algorithm adds vertices twice, records extra edges, and the result is no longer a tree.
Storing each edge in one direction only
Prim's algorithm walks outward from whatever it has visited, so an undirected edge must appear in both endpoints' adjacency lists. If you add only adj[u].append((v, w)), some vertices can become unreachable from the start, depending on which direction each edge was stored.
Expecting a spanning tree of a disconnected graph
Prim's algorithm only reaches vertices connected to start. On a disconnected graph it returns an MST of that one component and gives no warning. Check len(mst) == n - 1 if you need to detect this. A later chapter shows how to build a minimum spanning forest.
Edge Cases That Work Without Extra Code
- Parallel edges: both copies are pushed. The lighter one is popped first, and the heavier becomes stale.
- Self-loops: when
vis processed,vis already visited, so a loop edgev–vis never pushed. - Negative or zero weights: the cut property does not depend on weights being positive, so Prim's still works. This differs from Dijkstra's algorithm, whose code looks similar but which fails with negative weights.
- Single vertex: the loop pops the start entry, finds no neighbors, and returns
(0, []).
Exercises
Exercise
Run prim(adj, start=3) on the example graph by hand. List the edges in the order they are recorded and give the total.
Show answer
Pop (0,3,−1) and push (2,1,3) and (5,2,3). Pop (2,1,3) and record (3,1,2); push (1,0,1) and (3,2,1). Pop (1,0,1) and record (1,0,1); push (4,2,0). Pop (3,2,1) and record (1,2,3). The remaining entries (4,2,0) and (5,2,3) are stale. The edges are [(3,1,2), (1,0,1), (1,2,3)] with total 6. The edge set matches the run from vertex 0, though the order differs.
Exercise
Someone changes the push loop to set visited[u] = True right before heapq.heappush. What does prim(adj) return on the example graph, and why?
Show answer
Visiting 0 marks both 1 and 2 as visited, with entries (1,1,0) and (4,2,0). Popping them records 0–1 and 0–2, and the edge 1–3 gets pushed while 3 is still unvisited. The result is total 1 + 4 + 2 = 7 with edges [(0,1,1), (0,2,4), (1,3,2)]. Vertex 2 was locked in through its first edge, weight 4, before the lighter weight-3 edge from vertex 1 was seen.
Exercise
Add a fifth vertex 4 with no edges to the example (n = 5, adj[4] = []). What does prim(adj) return, and how would you detect that the graph is not connected?
Show answer
It returns (6, [(0, 1, 1), (1, 3, 2), (1, 2, 3)]). Vertex 4 is never pushed, so it is silently left out. Check len(mst) == n - 1, or check that all(visited) holds at the end. Here len(mst) is 3, but n - 1 is 4.