Minimum Spanning Trees (DSA #22)
You are laying fibre to connect every town in a region, paying per kilometre of cable. You need every town connected and you want to spend the least — which roads do you build? That is the minimum spanning tree problem: given a connected, weighted, undirected graph, choose a subset of edges that connects all vertices with minimum total weight and no cycles. Two classic greedy algorithms solve it: Kruskal (sort edges, add if they do not cycle) and Prim (grow one tree outward from a start).
What a spanning tree is
A spanning tree of a connected graph is a subset of edges that connects every vertex using exactly \(V - 1\) edges and no cycles. A minimum spanning tree (MST) is a spanning tree of least total weight (if weights are distinct, it is unique).
Two facts make the problem tractable:
- Cut property. For any partition of the vertices into two sets, the cheapest edge crossing the cut belongs to some MST.
- Cycle property. The most expensive edge in any cycle is never in an MST.
Both algorithms are direct consequences of the cut property.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick},
m/.style={->, very thick, green!55!black}]
\node[n, fill=orange!22] (a) at (0,0) {A};
\node[n, fill=blue!12] (b) at (2,0.6) {B};
\node[n, fill=blue!12] (c) at (2,-1.0) {C};
\node[n, fill=blue!12] (d) at (4,0) {D};
\draw[gray] (a) -- node[above, font=\scriptsize] {4} (b);
\draw[gray] (a) -- node[below, font=\scriptsize] {1} (c);
\draw[gray] (b) -- node[above, font=\scriptsize] {5} (d);
\draw[gray] (c) -- node[below, font=\scriptsize] {3} (d);
\draw[gray] (b) -- node[right, font=\scriptsize] {2} (c);
\draw[m] (a) -- (c); \draw[m] (c) -- (b); \draw[m] (c) -- (d);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2,-1.5) {MST edges 1 + 2 + 3 = 6 (skip the weight-4 edge)};
\end{tikzpicture}
Kruskal: sort edges, union-find
Kruskal’s algorithm is the cut property in its most literal form. Sort all edges by weight and add each one unless it would create a cycle — which we test with Union-Find (Chapter 17).
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path compression
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
def kruskal(n, edges):
edges.sort(key=lambda e: e[2]) # by weight
uf, mst, total = UnionFind(n), [], 0
for u, v, w in edges:
if uf.union(u, v): # adds an edge only if it connects two sets
mst.append((u, v, w))
total += w
if len(mst) == n - 1: # spanning tree complete
break
return total, mst
Sorting dominates: \(O(E \log E)\). Union-Find operations are effectively constant. Kruskal is the easier algorithm to implement and the best choice for sparse graphs.
Prim: grow one tree with a heap
Prim’s algorithm starts from an arbitrary vertex and repeatedly adds the cheapest edge that connects a new vertex to the growing tree. A min-heap tracks the best crossing edge.
import heapq
def prim(graph, start):
visited = set([start])
heap = [(w, start, v) for v, w in graph[start]]
heapq.heapify(heap)
total = 0
while heap:
w, u, v = heapq.heappop(heap)
if v in visited: # edge to an already-included vertex
continue
visited.add(v)
total += w
for nxt, wt in graph[v]:
if nxt not in visited:
heapq.heappush(heap, (wt, v, nxt))
return total
Cost is \(O(E \log V)\) with a binary heap, and it is often faster than Kruskal on dense graphs because it never sorts all edges.
Kruskal vs Prim
| Kruskal | Prim | |
|---|---|---|
| Strategy | global sorted edges | grow one tree |
| Data structure | Union-Find | min-heap |
| Time | \(O(E \log E)\) | \(O(E \log V)\) |
| Best for | sparse graphs, edge list | dense graphs |
| Extra | detects forest if disconnected | needs a start vertex |
Both are greedy and both are correct by the cut property. If the graph is disconnected, Kruskal naturally produces a minimum spanning forest; Prim only spans the connected component containing the start.
Why greed is safe here
The exchange argument (Chapter 25) explains it. Take the cheapest edge \(e\) crossing any cut. Suppose an MST \(T\) does not contain \(e\). Adding \(e\) to \(T\) creates a cycle, and that cycle must cross the cut another time via some edge \(e'\). Swapping \(e'\) for \(e\) keeps the tree spanning and cannot increase its weight, since \(e\) is the cheapest crossing edge. So some MST contains \(e\) — adding it is safe.
Where MSTs are used
- Network design. Laying cable, roads, pipelines, or circuits for minimum cost.
- Clustering. Run Kruskal and stop before the last few merges; the resulting components are clusters (single-linkage clustering).
- Approximation. The MST is a 2-approximation for the metric travelling-salesman problem and the basis of the Christofides algorithm.
- Image segmentation. Pixels as vertices, similarity as edge weights; MST-based cuts partition regions.
- Network broadcast routing.
Pitfalls
- Assuming disjoint edge weights. With ties there can be several MSTs with the same total; all are valid.
- Not checking connectivity. Prim against a disconnected graph silently spans only one component; Kruskal returns a forest.
- Wrong union-find. Without path compression or union by rank, Kruskal’s cycle test becomes slow and can dominate the sort.
- Confusing MST with shortest path. An MST minimises total edge weight, not the distance between two vertices; the shortest path between two nodes is generally not along MST edges.
- Forgetting the early exit. Kruskal can stop after \(V-1\) edges; continuing wastes time.
What is the cut property, and how does each algorithm exploit it? When would you choose Prim over Kruskal?
ASolution
The cut property says the cheapest edge crossing any partition belongs to some MST. Kruskal processes edges cheapest-first and adds any edge connecting two components (a cut), testing with Union-Find; Prim repeatedly takes the cheapest edge leaving the current tree, which is also a cut. Choose Prim for dense graphs (no full sort, heap-based) and Kruskal for sparse graphs or edge-list input.
Next: Recursion and Backtracking (DSA #23) — searching a solution space and pruning it.