Computer Science · Lesson 15
Minimum Spanning Tree
How do you connect ten cities with roads, cables, or pipes using the least total material? That's the minimum spanning tree problem — a classic in graph theory that has routed internet cables, power grids, airline networks, and water systems across the world.
Kruskal and Prim — Two Paths to the Same Answer
In 1956, mathematician Joseph Kruskal published an elegant greedy algorithm: sort all edges in a graph by weight, then keep adding the cheapest edge that doesn't create a cycle — until every node is connected. One year later in 1957, computer scientist Robert Prim independently found a different approach: start from any node, and repeatedly add the cheapest edge that connects the current tree to a node not yet in it. Both algorithms always produce the same optimal result — the minimum spanning tree — and both are provably correct. Their work appears in network design, biology, image segmentation, and cluster analysis to this day.
Graphs, Spanning Trees, and Minimality
Spanning tree — a subgraph that connects all nodes with no cycles (uses exactly n−1 edges)
Minimum spanning tree — the spanning tree with the smallest possible total edge weight
Cycle — a path that starts and ends at the same node (adding one creates redundancy)
Kruskal's Algorithm — Step by Step
- 1List all edges in the graph sorted by weight, cheapest first.
- 2Consider each edge in order. Ask: would adding this edge create a cycle?
- 3If no cycle — add it to the MST (shown in green).
- 4If it would create a cycle — reject it (shown in red).
- 5Stop when n−1 edges have been added. All nodes are now connected.
This is a greedy algorithm — it always makes the locally cheapest choice at each step. Remarkably, this greedy strategy is provably globally optimal for spanning trees.
Kruskal's Algorithm Visualiser
Click Step to add one edge at a time, or Run All to complete instantly. Green edges are in the MST; red edges were rejected (would create a cycle); grey edges have not yet been considered.
Real-World Applications
Practice Problems
Easy1. A spanning tree for a graph with n nodes has exactly how many edges?
Easy2. Kruskal's algorithm considers edges in what order?
Medium3. A graph has 5 nodes and edges with weights 2, 3, 4, 5, 6, and 7. The MST needs 4 edges. What is the minimum possible MST total weight?
Medium4. What property makes a path a "cycle" in graph theory?
Challenge5. Prim's algorithm grows the MST by always adding the cheapest edge connecting the current tree to a new node. For a graph with n = 6 nodes, how many steps (edge additions) does Prim's take to complete the MST?