Minimum Spanning Tree Intro
Imagine you must connect six villages with fibre-optic cable. You know what each possible connection would cost. Which connections should you build so that every village is connected (directly or through others) and the total cost is as small as possible?
That is the minimum spanning tree (MST) problem. Given a connected, undirected, weighted graph:
- A spanning tree is a subset of the edges that connects all
Vvertices and contains no cycle. It always has exactlyV - 1edges. - A minimum spanning tree is a spanning tree whose total weight is as small as possible.
A cycle is never needed: if the chosen edges contained one, you could remove any edge of the cycle and everything would stay connected, at a lower cost.
The example graph
This graph is used in this lesson and the next two:
| Vertex | Edges (neighbour: weight) |
|---|---|
| A | B: 7, C: 3 |
| B | A: 7, C: 2, D: 5 |
| C | A: 3, B: 2, D: 6, E: 4 |
| D | B: 5, C: 6, E: 8, F: 1 |
| E | C: 4, D: 8, F: 9 |
| F | D: 1, E: 9 |
Edges and weights: A-B 7, A-C 3, B-C 2, B-D 5, C-D 6, C-E 4, D-E 8, D-F 1, E-F 9.
Checking a spanning tree
edges = {("A", "B"): 7, ("A", "C"): 3, ("B", "C"): 2, ("B", "D"): 5, ("C", "D"): 6,
("C", "E"): 4, ("D", "E"): 8, ("D", "F"): 1, ("E", "F"): 9}
vertices = "ABCDEF"
def is_spanning_tree(chosen):
if len(chosen) != len(vertices) - 1:
return False
group = {v: v for v in vertices} # tiny union-find
def find(x):
while group[x] != x:
x = group[x]
return x
for a, b in chosen:
ra, rb = find(a), find(b)
if ra == rb:
return False # this edge closes a cycle
group[ra] = rb
return True
def weight(chosen):
return sum(edges[e] for e in chosen)
guess = [("A", "B"), ("A", "C"), ("C", "D"), ("D", "F"), ("E", "F")]
best = [("D", "F"), ("B", "C"), ("A", "C"), ("C", "E"), ("B", "D")]
for name, chosen in [("guess", guess), ("best", best)]:
print(name, is_spanning_tree(chosen), weight(chosen))guess True 26
best True 15
Both choices connect everything, but the second one costs 15 instead of 26.
Brute force: try every spanning tree
For a tiny graph we can try every subset of V - 1 edges and keep the cheapest valid one. This proves 15 is optimal here, but the number of subsets explodes quickly, so real algorithms must be smarter.
from itertools import combinations
edges = {("A", "B"): 7, ("A", "C"): 3, ("B", "C"): 2, ("B", "D"): 5, ("C", "D"): 6,
("C", "E"): 4, ("D", "E"): 8, ("D", "F"): 1, ("E", "F"): 9}
vertices = "ABCDEF"
def connects_all(chosen):
reached, frontier = {"A"}, ["A"]
while frontier:
u = frontier.pop()
for a, b in chosen:
for x, y in ((a, b), (b, a)):
if x == u and y not in reached:
reached.add(y)
frontier.append(y)
return len(reached) == len(vertices)
trees = [c for c in combinations(edges, len(vertices) - 1) if connects_all(c)]
best = min(trees, key=lambda c: sum(edges[e] for e in c))
print("spanning trees:", len(trees), "of", len(list(combinations(edges, 5))), "subsets")
print("cheapest:", sorted(best), sum(edges[e] for e in best))spanning trees: 55 of 126 subsets
cheapest: [('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E'), ('D', 'F')] 15
The cut property: why greedy works
Split the vertices into two groups in any way (a cut). Of all edges that cross from one group to the other, the cheapest one belongs to an MST. Intuition: some edge must cross the cut to connect the groups, and swapping any more expensive crossing edge for the cheapest one can only lower the total.
Both classic MST algorithms are greedy: they repeatedly add the cheapest edge that is safe according to the cut property.
| Algorithm | Grows | Picks next | Needs | Time |
|---|---|---|---|---|
| Prim's | one tree from a start vertex | cheapest edge leaving the tree | a priority queue | O(E log V) |
| Kruskal's | a forest that merges into one tree | cheapest edge overall that doesn't close a cycle | sorting + union-find | O(E log E) |
Uses of minimum spanning trees
- Designing networks: cables, pipes, roads, electrical grids.
- Clustering: build the MST, then delete the
k - 1most expensive edges to getkgroups of similar items. - Approximating hard problems: an MST gives a tour at most twice the optimum for the metric Traveling Salesman problem.
- Image segmentation and analysing networks of similar documents or genes.
Note: If all edge weights are different, the MST is unique. With equal weights there can be several MSTs, all with the same total weight.
Test yourself
How many edges does a spanning tree of a graph with 10 vertices have?
- 9
- 10
- 11
- 45
Why can a minimum spanning tree never contain a cycle?
- Cycles are not allowed in graphs
- Removing one cycle edge keeps everything connected and lowers the cost
- Cycles make the graph directed
- It can, if the weights are small
What does the cut property say?
- The most expensive edge is in every MST
- The cheapest edge crossing any cut belongs to an MST
- Every cut has exactly one edge
- MSTs are unique