Graph - Prim's Minimum Spanning Tree (MST)
Connect every vertex of a weighted graph at the lowest total cost by growing one tree, cheapest edge first.
Given nn{u, v, weight}
Example 1
Output: 70
Explanation: the edges 1-3, 1-2 and 3-4 connect all four vertices, and 10 + 20 + 40 = 70.
Example 2
Output: -1
Explanation: no edge joins vertex 1 or 2 to vertex 3 or 4.
The Idea
Picture four villages and the roads that could be paved between them, each with a price. A road between villages 1 and 2 costs 20, between 1 and 3 costs 10, between 2 and 3 costs 30, between 3 and 4 costs 40, and between 1 and 4 costs 50. Every village must be able to reach every other one, perhaps through a third village, for as little money as possible. That is Example 1: each village is a vertex, each road is an edge, and its price is the edge's weight.
How many roads does the cheapest plan use? Four villages need three. Each useful road brings in a village that was not connected before, and once all four are connected, any extra road closes a loop such as 1-2, 2-3 and 3-1. One road of that loop could be left out and everything would still be connected. A set of edges that connects every vertex and has no loop is called a spanning tree, and the cheapest one is a minimum spanning tree, or MST.
The slow way is to try every pick of three edges. Example 1 has five edges, so there are 10 picks. Eight of them are spanning trees, and the other two are loops: 1-2, 1-3, 2-3 weighs only 60, but it never reaches vertex 4. The cheapest of the eight trees is 1-2, 1-3 and 3-4, at 70. With 20 vertices and 50 edges, though, there are about 3 × 1013 picks of 19 edges. Can the tree be built one good edge at a time instead?
It can, by growing it from one vertex. Start with vertex 1 alone. The edges that leave it are 1-2 for 20, 1-3 for 10 and 1-4 for 50, so take the cheapest, 1-3, and vertex 3 joins. Now the group is {1, 3}, and the edges leaving it are 1-2 for 20, 2-3 for 30, 3-4 for 40 and 1-4 for 50. The cheapest of these, 1-2, brings in vertex 2. Last, 3-4 for 40 beats 1-4 for 50, and vertex 4 joins, for a total of 70.
Why is the cheapest edge leaving the group always a safe pick? Suppose a best tree leaves it out. Adding it to that tree closes a loop, and the loop has to cross from the group to the outside a second time, through some other edge. Removing that other edge leaves a spanning tree again, and the swap cannot make it heavier, because the edge taken out cost at least as much.
Taking 1-3 just because it is the cheapest edge in reach right now, and never undoing that, is called a greedy choice. The swap argument shows that this greedy choice never costs extra. Growing one tree from a start vertex, always by the cheapest edge leaving it, is Prim's algorithm.
One question is left: how do we find the cheapest leaving edge at each step without rereading every edge? Keep the candidate edges in a min-heap, a collection that always hands back its smallest entry first. Each time a vertex joins, its edges to vertices outside the group go into the heap.
On the left of the picture, the three orange edges are the tree, marked 1st, 2nd and 3rd in the order they joined. The table on the right shows the same run through the heap, one row per entry it gives, written as vertex:weight. The row labelled 2:30 is grey: that entry came from edge 2-3 when vertex 3 joined, but by the time the heap gives it, vertex 2 is already in the tree through 1-2.
Solution Approach
The code needs four decisions: how to store the graph, what a heap entry holds, what to do with an entry for a vertex that has already joined, and when to stop.
Storing the graph as an adjacency list
When a vertex joins, how does the code find the edges that leave it? It keeps an adjacency list: for each vertex, a list of its neighbours with the weight of the edge to each. Every edge goes into both endpoints' lists, because the tree may reach either end first. Written as neighbour:weight, the lists for Example 1 are 2:20, 3:10, 4:50 for vertex 1, then 1:20, 3:30 for vertex 2, then 1:10, 2:30, 4:40 for vertex 3, and 3:40, 1:50 for vertex 4.
What if each edge went only into the list of its first vertex? On Example 1 the run still returns 70, but only by luck: vertex 1's list alone reaches 2, 3 and 4, and vertex 3's list keeps 3-4. The same five edges written the other way round, such as [2, 1, 20]
What a heap entry holds
Which part of an edge does the heap need? Only the vertex it would bring in and the edge's weight, so each entry is an int[]{vertex, weight}PriorityQueue
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
The start vertex goes in as {1, 0}
Dijkstra's shortest path algorithm also grows outward from a start vertex with a heap, and the two are easy to mix up. Its heap key is the whole distance from the start. Prim's key is the weight of one edge, because a vertex only has to be attached to the tree somewhere, not reached cheaply from vertex 1.
Skipping vertices that already joined
Can the heap hold two entries for the same vertex? Yes. When vertex 3 joined, it pushed 2:30, while 2:20 from vertex 1 was still waiting. A PriorityQueue
The cost is that later entries for the same vertex are out of date. A booleaninTree
When to stop
The code stops taking entries from the heap as soon as all nn
Java Solution
The method minimumSpanningTreeWeight
- First, build the adjacency list
: one list per vertex from 0 toadj , with index 0 unused. A loop overn adds each edge to the lists of both its ends, as aedges pair.{neighbour, weight} - Create the array
and the min-heapinTree , and pushheap for the start vertex. Two counters start at 0:{1, 0} for the weight so far andtotal for the vertices that have joined.added - A
loop runs as long as the heap is not empty andwhile is belowadded . Each time round, poll the entry with the smallest weight inton , and call its vertextop . Ifu is already true, skip the entry.inTree[u] - Otherwise
joins: mark it inu , add the entry's weight toinTree and increasetotal . Then a loop overadded 's list pushesu for every neighbour not yet in the tree.{neighbour, weight} - After the loop, return
if alltotal vertices joined, and -1 if not.n
The main
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class Prim {
// Vertices are 1..n. Each edge is {u, v, weight} and works both ways.
// Returns the total weight of a minimum spanning tree, or -1 if the graph is not connected.
public static int minimumSpanningTreeWeight(int n, int[][] edges) {
List<List<int[]>> adj = new ArrayList<>();
for (int v = 0; v <= n; v++) {
adj.add(new ArrayList<>());
}
for (int[] e : edges) {
adj.get(e[0]).add(new int[] {e[1], e[2]}); // u can reach v
adj.get(e[1]).add(new int[] {e[0], e[2]}); // and v can reach u
}
boolean[] inTree = new boolean[n + 1];
// {vertex, weight of the edge that would bring it in}, smallest weight first
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
heap.add(new int[] {1, 0}); // vertex 1 joins for free
int total = 0;
int added = 0;
while (!heap.isEmpty() && added < n) {
int[] top = heap.poll();
int u = top[0];
if (inTree[u]) {
continue; // a cheaper edge already brought u in
}
inTree[u] = true;
total += top[1];
added++;
for (int[] next : adj.get(u)) {
if (!inTree[next[0]]) {
heap.add(new int[] {next[0], next[1]}); // an edge from the tree to outside
}
}
}
return added == n ? total : -1;
}
public static void main(String[] args) {
int[][] example1 = {{1, 2, 20}, {1, 3, 10}, {2, 3, 30}, {3, 4, 40}, {1, 4, 50}};
System.out.println("Example 1: " + minimumSpanningTreeWeight(4, example1));
int[][] example2 = {{1, 2, 5}, {3, 4, 7}};
System.out.println("Example 2: " + minimumSpanningTreeWeight(4, example2));
System.out.println("one vertex, no edges: " + minimumSpanningTreeWeight(1, new int[0][]));
int[][] square = {{1, 2, 1}, {2, 3, 1}, {3, 4, 1}, {4, 1, 1}};
System.out.println("square, all weights 1: " + minimumSpanningTreeWeight(4, square));
int[][] twoRoads = {{1, 2, 9}, {1, 2, 4}};
System.out.println("two edges 1-2, 9 and 4: " + minimumSpanningTreeWeight(2, twoRoads));
}
}
Running it prints:
Example 1: 70
Example 2: -1
one vertex, no edges: 0
square, all weights 1: 3
two edges 1-2, 9 and 4: 4
Example 1 gives 70, the same total as the last row of the table in the picture, and Example 2 gives -1 because only vertices 1 and 2 ever join. A single vertex with no edges is already a spanning tree on its own, so its total is 0: the start entry {1, 0}added
The square has four edges of weight 1 but returns 3. Its four edges form one loop, so the tree keeps three of them, and with equal weights any three will do. The last line has two edges between the same pair of vertices, weighing 9 and 4. Both entries go into the heap, the 4 comes out first and brings in vertex 2, and the entry for the 9 edge is never polled.
Complexity
The work is building the adjacency list, plus the heap pushes and polls, and the edges decide how many of those there are. Here V is the number of vertices and E the number of edges.
- Time: O(V + E log E), because building the lists touches each vertex and edge once, and each edge pushes at most two heap entries, one from each end, at O(log E) per push or poll. When no two edges join the same pair of vertices, E is below V2, so log E is below 2 log V and the bound becomes the usual O(E log V) for a connected graph.
- Space: O(V + E), because the adjacency list holds two entries per edge,
holds one flag per vertex, and the heap can hold up to 2E + 1 entries at once.inTree
Building the same tree by sorting all the edges first and adding them cheapest first, while skipping any edge that would close a loop, is