Given a connected, undirected, weighted graph, find a spanning tree with minimum total edge weight.
A spanning tree connects all $n$ vertices using exactly $n-1$ edges with no cycles.
Applications:
- Designing cheapest network (electrical grid, fibre optic cable, road networks)
- Cluster analysis
- Approximation algorithms for TSP
Input: Connected, undirected, weighted graph $G = (V, E, w)$, starting vertex $s$
Output: A minimum spanning tree — a set of $n-1$ edges with minimum total weight
Precondition: Graph must be connected (otherwise no spanning tree exists)
Prim’s grows the MST one edge at a time, always adding the cheapest edge connecting a vertex in the MST to a vertex outside it.
ALGORITHM Prim(graph, start)
mst_edges ← empty set
visited ← {start}
pq ← PriorityQueue of edges from start (sorted by weight)
while visited ≠ all vertices do
(u, v, w) ← removeMin(pq) // cheapest available edge
if v NOT in visited then
add (u, v, w) to mst_edges
add v to visited
for each edge (v, x, wx) where x NOT in visited do
insert (v, x, wx) into pq
end for
end if
end while
return mst_edges
Graph with vertices {A, B, C, D} and edges:
- A–B: 4, A–C: 2, B–C: 1, B–D: 5, C–D: 8
Starting at A:
1. Visited: {A}. Available edges: (A–B, 4), (A–C, 2)
2. Add cheapest: A–C (weight 2). Visited: {A, C}
3. Available: (A–B, 4), (C–B, 1), (C–D, 8)
4. Add cheapest: C–B (weight 1). Visited: {A, B, C}
5. Available: (A–B, 4 — duplicate, skip), (B–D, 5), (C–D, 8)
6. Add cheapest: B–D (weight 5). Visited: {A, B, C, D} ✓
MST edges: {A–C, C–B, B–D}, total weight = 2 + 1 + 5 = 8
Prim’s correctness relies on the cut property:
For any cut (partition of vertices into two sets), the minimum-weight edge crossing the cut belongs to some MST.
At each step, Prim’s maintains a cut: {visited} vs {unvisited}. Adding the minimum edge across this cut is always safe (proven by contradiction: if a cheaper spanning tree existed, swapping would not reduce cost).
| Implementation | Complexity |
|---|---|
| Simple (array) | $O(V^2)$ |
| Binary heap + adjacency list | $O((V + E) \log V)$ |
| Fibonacci heap | $O(E + V \log V)$ |
For sparse graphs, heap-based Prim’s is much faster.
EXAM TIP: In exams, trace Prim’s step by step, showing the priority queue state, which edge is added, and the set of visited vertices at each step. Marks are awarded for correct tracing, not just the final answer.
VCAA FOCUS: Know the greedy nature of Prim’s and its connection to the cut property. Be able to argue why it produces a minimum spanning tree.