Sub topic 14
Minimum spanning trees: a first look
This chapter assumes you can read the adjacency-list dictionaries from earlier chapters, know what connected components are, and are comfortable with sorting and big-O notation.
The problem
Suppose you must connect several offices with network cable. Each possible cable run has a cost. You want every office reachable from every other, at the lowest total cost.
Model the offices as vertices and the possible runs as weighted, undirected edges. You want a subset of edges that connects all vertices and has the smallest total weight. That subset is a minimum spanning tree (MST).
- A spanning tree is a set of edges that connects every vertex and contains no cycle.
- A graph with V vertices has spanning trees of exactly V − 1 edges.
- An MST is a spanning tree whose total weight is the smallest possible.
The graph must be connected. If it is not, no spanning tree exists. You can instead compute a spanning forest, with one tree per component.
Why the result is a tree
If the chosen edges contained a cycle, you could remove any edge on it. The vertices would stay connected, and with non-negative weights the total would not increase. So a cheapest connecting set never needs a cycle. A connected graph with no cycles is a tree.
An MST is not always unique. If several edges share a weight, different trees can tie for the minimum total.
The graph for the example
Kruskal's algorithm
Kruskal's algorithm builds the tree greedily:
- Sort all edges by weight, lightest first.
- Take each edge in order.
- Keep the edge if its endpoints are in different components. Skip it otherwise, because it would close a cycle.
To check whether two vertices share a component quickly, use a union-find structure. It stores a parent pointer for each vertex. Following pointers to the root tells you which component a vertex is in.
def kruskal(vertices, edges):
parent = {v: v for v in vertices}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
tree = []
total = 0
for w, u, v in sorted(edges):
root_u, root_v = find(u), find(v)
if root_u != root_v:
parent[root_u] = root_v
tree.append((u, v, w))
total += w
return tree, total
edges = [(4, "A", "B"), (1, "A", "C"), (2, "C", "B"),
(5, "B", "D"), (3, "C", "D")]
print(kruskal("ABCD", edges))
# ([('A', 'C', 1), ('C', 'B', 2), ('C', 'D', 3)], 6)The algorithm keeps A–C, C–B, and C–D. It then skips A–B (weight 4), because A and B are already connected through C, and B–D (weight 5) for the same reason.
The edge list here is a flat list of (weight, u, v) tuples, not the adjacency dictionary from earlier chapters. Kruskal's algorithm processes edges globally, so a flat list suits it. Sorting dominates the running time, giving O(E log E).
Prim's algorithm, briefly
Prim's algorithm grows one tree from a start vertex. At each step it adds the cheapest edge leaving the tree. It uses a priority queue, much like Dijkstra's algorithm, and works directly on an adjacency list. It runs in O(E log V) with a binary heap.
Common errors
- Confusing MST with shortest paths. An MST minimizes total weight over the whole tree. Dijkstra's algorithm minimizes the distance from one source to each vertex. In the example, the MST path from A to B costs 1 + 2 = 3, but on other graphs the MST path between two vertices can be longer than their shortest path.
- Applying it to directed graphs. The ideas here are for undirected graphs. Directed graphs need a different problem, the minimum spanning arborescence, with different algorithms.
- Ignoring disconnected input. If the result has fewer than V − 1 edges, the graph was not connected.
Exercise
A connected undirected graph has 10 vertices. How many edges does any spanning tree of it have, and how does Kruskal's algorithm decide to skip an edge?
Show answer
Any spanning tree has 10 − 1 = 9 edges. Kruskal's algorithm skips an edge when both endpoints are already in the same component, because adding it would create a cycle.