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 understand sorting and heaps at the level of "heapq gives me the smallest item". It introduces one new problem, which is connecting every vertex as cheaply as possible, and two algorithms that solve it.
The problem
Suppose you must lay cable between five offices. Each possible cable run has a cost. You want every office reachable from every other, and you want the lowest total cost.
Model the offices as vertices and the possible runs as weighted, undirected edges. You are looking for a subset of edges that:
- connects all vertices,
- contains no cycle,
- has the smallest possible total weight.
That subset is a minimum spanning tree (MST). A spanning tree of a connected graph is a set of edges that touches every vertex, keeps the graph connected, and has no cycle. A graph with n vertices always gives a spanning tree with exactly n - 1 edges. An MST is the spanning tree with the lowest total weight.
Why no cycles? Any edge on a cycle can be removed without disconnecting anything. With positive weights, removing it also lowers the cost. So a cheapest connection never needs a cycle.
An example graph
This graph has four vertices and five edges:
Any spanning tree needs three edges. Picking A-C, C-B, and B-D costs 1 + 2 + 5 = 8. Picking A-B, A-C, and C-D costs 4 + 1 + 8 = 13. The first choice is cheaper, and you can check that no choice beats 8.
What an MST needs from the graph
- Undirected edges. The usual MST algorithms assume a symmetric relationship. A directed graph has a different problem, the minimum spanning arborescence, which needs other algorithms. It is outside this chapter.
- Connectivity. A spanning tree exists only if the graph is connected. If it is not, the algorithms below give a spanning forest, with one tree per component.
- Weights. In an unweighted graph every spanning tree has
n - 1edges and so costs the same. Weights are what make one tree better than another.
Negative weights are fine for MSTs, unlike for Dijkstra's algorithm. The algorithms only compare edge weights. They never add weights along a path.
Why a greedy approach works
Both algorithms in this chapter are greedy: they repeatedly take the cheapest edge that is safe. The justification is the cut property.
A cut splits the vertices into two non-empty groups. Take the lightest edge that crosses between the groups. If that edge is strictly lighter than every other crossing edge, it belongs to every MST. If several crossing edges tie for lightest, some MST contains one of them. Either way, taking the lightest crossing edge never rules out an optimal tree.
Kruskal's and Prim's algorithms differ only in which cut they examine at each step.
Kruskal's algorithm
Kruskal's algorithm works on edges globally:
- Sort all edges by weight.
- Go through them from lightest to heaviest.
- Keep an edge if its endpoints are currently in different components. Skip it if they are in the same component, because it would close a cycle.
To answer "same component?" quickly, it uses a union-find structure (also called disjoint sets). Each vertex points toward a representative of its component. find follows pointers to the representative. Joining two components makes one representative point to the other.
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
def kruskal(graph):
# Each undirected edge appears twice in the adjacency list,
# so keep only the copy where u < v. This also drops self-loops.
edges = sorted(
(w, u, v) for u in graph for v, w in graph[u].items() if u < v
)
parent = {v: v for v in graph}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
tree, total = [], 0
for w, u, v in 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
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
add_edge(weighted, "B", "D", 5)
add_edge(weighted, "C", "D", 8)
print(kruskal(weighted)) # ([('A', 'C', 1), ('B', 'C', 2), ('B', 'D', 5)], 8)Walking through the sorted edges:
| Edge | Weight | Same component before? | Action |
|---|---|---|---|
| A-C | 1 | No | Keep |
| B-C | 2 | No | Keep |
| A-B | 4 | Yes (A, C, B joined) | Skip |
| B-D | 5 | No | Keep |
| C-D | 8 | Yes | Skip |
The cost is dominated by sorting, so it is O(E log E), which is the same as O(E log V) because E is at most V². Union-find with path halving adds almost nothing on top.
Prim's algorithm
Prim's algorithm grows a single tree from a start vertex. At each step it adds the cheapest edge that leaves the tree and reaches a new vertex. The cut is always "vertices already in the tree" versus "all others".
It looks like Dijkstra's algorithm, and it uses the same heap. The difference is the priority. Dijkstra orders vertices by total distance from the source. Prim orders them by the weight of the single edge that connects them to the tree.
import heapq
def prim(graph, start):
visited = {start}
heap = [(w, start, v) for v, w in graph[start].items()]
heapq.heapify(heap)
tree, total = [], 0
while heap:
w, u, v = heapq.heappop(heap)
if v in visited:
continue # stale entry: v joined the tree by a cheaper edge
visited.add(v)
tree.append((u, v, w))
total += w
for x, wx in graph[v].items():
if x not in visited:
heapq.heappush(heap, (wx, v, x))
return tree, total
print(prim(weighted, "A")) # ([('A', 'C', 1), ('C', 'B', 2), ('B', 'D', 5)], 8)The tree has the same edges and the same total, 8, as Kruskal's result. Only the order and the endpoint orientation differ. With a binary heap the cost is O(E log V).
If the graph is disconnected, Prim's algorithm stops after covering the start vertex's component. To get a full spanning forest, rerun it from each unvisited vertex.
Kruskal or Prim
| Question | Kruskal | Prim |
|---|---|---|
| Works from | The sorted global edge list | A growing tree |
| Needs | Union-find | A priority queue |
| Disconnected graph | Returns a forest automatically | Covers one component per start |
| Natural fit | Sparse graphs, edge lists | Dense graphs, adjacency lists |
For most programs the two are interchangeable. Choose by what your data already looks like: an edge list suggests Kruskal, and an adjacency list you are already traversing suggests Prim.
Edge cases and common errors
- MST is not a shortest-path tree. In the example, the MST path from A to D is A-C-B-D with cost 8. The direct route A-B-D costs 9 and A-C-D costs 9, so here the MST path happens to be shortest. This is a coincidence. In general an MST minimizes the total weight of the whole structure, not the distance from any one vertex. Use Dijkstra for distances.
- Ties. When several edges share a weight, the MST may not be unique. Different algorithms, or different tie-breaking orders, may return different trees. All of them have the same total weight.
- Unique weights. If all edge weights are distinct, the MST is unique.
- Forgetting the connectivity check. If
len(tree) < n - 1, the graph was disconnected and you got a forest. Check this before treating the result as a spanning tree. - Applying it to directed edges. Running these functions on a graph built with
directed=Trueproduces meaningless output, since the adjacency list is no longer symmetric. - Counting edges twice. An undirected adjacency list stores each edge in both directions. Summing every entry doubles the weights.
Where MSTs are used
- Designing networks of cable, pipe, or road with minimum total length.
- Clustering: build an MST over points, then delete the heaviest edges to split the points into groups.
- Approximating hard problems, such as giving a rough route for the travelling salesman problem.
Exercises
Exercise
A connected undirected graph has 10 vertices and 25 edges. How many edges does any spanning tree of it contain, and how many edges does an MST algorithm discard?
Show answer
A spanning tree of a graph with 10 vertices has 10 - 1 = 9 edges. The algorithm discards 25 - 9 = 16 edges.
Exercise
Run Kruskal's algorithm by hand on edges P-Q 3, Q-R 1, P-R 2, R-S 4, Q-S 6. List the edges you keep, in order, and the total weight.
Show answer
Sorted order is Q-R 1, P-R 2, P-Q 3, R-S 4, Q-S 6. Keep Q-R (1) and P-R (2). Skip P-Q because P and Q are already connected through R. Keep R-S (4). Skip Q-S. The tree is Q-R, P-R, R-S with total weight 7.
Exercise
Why can Kruskal's and Prim's algorithms handle negative edge weights, while Dijkstra's algorithm cannot?
Show answer
MST algorithms only compare individual edge weights to decide which edge is cheapest across a cut, so a negative value just sorts first. Dijkstra's algorithm adds weights along a path and assumes a finalized vertex can never be improved later. A negative edge can break that assumption.