Sub topic 12
Minimum Spanning Trees with Kruskal and Prim
This chapter assumes you can read Python, know what a priority queue (heap) does, and are comfortable with graphs stored as edge lists or adjacency lists. It also builds on the exchange argument from earlier in the tutorial.
A spanning tree of a connected, undirected, weighted graph is a set of edges that connects every vertex without forming a cycle. A graph with n vertices has n − 1 edges in any spanning tree. A minimum spanning tree (MST) is a spanning tree with the smallest possible total weight. MSTs come up in network design, clustering, and as building blocks for approximation algorithms.
The Cut Property
Both algorithms in this chapter rest on one fact. A cut splits the vertices into two non-empty groups. An edge crosses the cut if its endpoints are in different groups.
Cut property: for any cut, the lightest edge crossing it belongs to some MST. If all weights are distinct, that edge belongs to every MST.
The proof is an exchange argument. Suppose an MST T leaves out the lightest crossing edge e. Adding e to T creates a cycle. That cycle must cross the cut a second time, through some edge f. Swap f for e. The result is still a spanning tree, and because w(e) ≤ w(f), its weight is no larger. So some MST contains e.
Kruskal's Algorithm
Kruskal sorts the edges by weight and adds each one unless it would close a cycle. A union-find structure tracks which vertices are already connected. When Kruskal accepts edge (u, v), take the cut between u's current component and everything else. No lighter edge crosses that cut, because any lighter edge was examined earlier and either joined two components or was skipped as internal to one. So the cut property applies.
def kruskal(n, edges):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
mst = []
for w, u, v in sorted(edges):
ru, rv = find(u), find(v)
if ru != rv:
parent[ru] = rv
mst.append((u, v, w))
return mst
edges = [(1, 0, 1), (4, 0, 2), (2, 1, 2), (6, 1, 3), (3, 2, 3)]
print(kruskal(4, edges)) # [(0, 1, 1), (1, 2, 2), (2, 3, 3)]Prim's Algorithm
Prim grows one tree from a start vertex. At each step it adds the lightest edge that leaves the tree. The cut here is "tree versus the rest", so the cut property applies directly.
import heapq
def prim(n, adj, start=0):
visited = [False] * n
heap = [(0, start, -1)]
mst = []
while heap:
w, v, u = heapq.heappop(heap)
if visited[v]:
continue
visited[v] = True
if u != -1:
mst.append((u, v, w))
for nxt, wt in adj[v]:
if not visited[nxt]:
heapq.heappush(heap, (wt, nxt, v))
return mst
edges = [(1, 0, 1), (4, 0, 2), (2, 1, 2), (6, 1, 3), (3, 2, 3)]
adj = [[] for _ in range(4)]
for w, u, v in edges:
adj[u].append((v, w))
adj[v].append((u, w))
print(prim(4, adj)) # [(0, 1, 1), (1, 2, 2), (2, 3, 3)]Comparing the Two
| Aspect | Kruskal | Prim (binary heap) |
|---|---|---|
| Running time | O(E log E) | O(E log V) |
| Input form | Edge list | Adjacency list |
| Grows | A forest that merges | One tree |
| Disconnected graph | Returns a minimum spanning forest | Spans only the start vertex's component |
| Good fit | Sparse graphs, edges already sorted | Dense graphs |
Common Errors
- Negative edge weights are fine for MSTs. Only the relative order of weights matters. Dijkstra's algorithm is different, as the next chapter shows.
- An MST does not give shortest paths between vertices. The tree path from 0 to 3 can be longer than the best direct route.
- With repeated weights, a graph can have more than one MST. Two correct programs can return different edge sets with the same total weight.
Exercise
Add 10 to every edge weight in a connected graph. Does the set of MST edges change? Then explain why this trick does not work for shortest paths.
Show answer
The MST edges stay the same. Every spanning tree has exactly n − 1 edges, so each one's total rises by the same 10(n − 1), and the sorted order of edges does not change. Shortest paths can differ in their number of edges, so a path with more edges gains more weight. That can change which path is shortest.
Exercise
Using the cut property, show that the heaviest edge on a cycle, if it is strictly heavier than every other edge on that cycle, is in no MST.
Show answer
Suppose an MST T contains that heaviest edge e. Remove e, which splits T into two components and defines a cut. The rest of the cycle reconnects the two sides, so another cycle edge f crosses the cut, and w(f) < w(e). Replacing e with f gives a spanning tree that weighs less than T, which contradicts T being minimum.