Lecture 23
What Is a Minimum Spanning Tree?
A minimum spanning tree (MST) of a connected, weighted, undirected graph is a subset of edges that:
- Connects all vertices (it is spanning)
- Contains no cycles (it is a tree, so exactly V−1 edges)
- Has the minimum possible total edge weight
Every connected graph has at least one MST. If all edge weights are distinct, the MST is unique.
The MST of the graph above uses edges 0-1(2), 1-2(3), 1-4(5), 0-3(6) for a total weight of 16. The heavier edges — 1-3(8), 2-4(7), 3-4(9) — are excluded.
Two greedy algorithms find the MST. They differ in what they sort and what data structure they use to avoid cycles.
Kruskal's Algorithm
Kruskal's builds the MST by considering edges in ascending weight order. An edge is added to the MST only if its two endpoints are in different components — that is, adding it would not create a cycle. Union Find from lecture 21 tracks which component each vertex belongs to.
Steps:
- Sort all edges by weight ascending.
- For each edge (u, v, w): if
find(u) != find(v), add the edge andunite(u, v). - Stop after V−1 edges have been added.
Kruskal's trace on the graph above:
Edges 2-4(7), 1-3(8), and 3-4(9) are never reached — Kruskal's stops as soon as V−1 edges are added. Sorting guarantees that the first V−1 edges that don't form a cycle are the minimum-weight ones.
Prim's Algorithm
Prim's builds the MST by growing it one vertex at a time from a starting vertex. At each step it picks the minimum-weight edge that crosses the cut — the boundary between vertices already in the MST and those not yet included. This is structurally identical to Dijkstra's, with edge weight replacing accumulated distance.
Steps:
- Mark the source vertex as in the MST; push all its edges onto a min-heap keyed by weight.
- Pop the minimum-weight edge
(w, v, from). If v is already in the MST, skip (stale). - Add the edge to the MST, mark v as in the MST, push v's edges.
- Repeat until V−1 edges have been added.
Prim's trace on the same graph starting at vertex 0:
For undirected graphs, add_edge(u, v, w) must add {v, w} to adj[u] and {u, w} to
adj[v]. Omitting one direction means some edges are invisible to the algorithm when it
expands from the neighbor's side.
Kruskal's vs Prim's
| Property | Kruskal's | Prim's |
|---|---|---|
| Input | Edge list | Adjacency list |
| Core operation | Sort edges, skip cycles | Grow from source, pick min cut |
| Supporting DS | Union Find | Min-heap |
| Time complexity | O(E log E) | O((V + E) log V) |
| Better for | Sparse graphs (few edges) | Dense graphs (many edges) |
Both are greedy and always produce a correct MST for connected graphs. The choice is usually driven by how the graph is stored.
Exercises
Q1.
Without running the code, predict what this program prints.
Q2.
Without running the code, predict what this program prints.
Q3.
Each snippet has a bug. Identify what's wrong.
Q4.
Implement kruskal for the edge list below.
Q5.
Implement prim for the graph below.