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 n vertices numbered 1 to n and a list of undirected edges, each written as {u, v, weight}, choose some of the edges so that every vertex can reach every other vertex through them. The total weight of the chosen edges must be as small as possible. Return that smallest total, or -1 when no choice of edges connects all the vertices.

Example 1
Input: n = 4, edges = [[1, 2, 20], [1, 3, 10], [2, 3, 30], [3, 4, 40], [1, 4, 50]]
Output: 70
Explanation: the edges 1-3, 1-2 and 3-4 connect all four vertices, and 10 + 20 + 40 = 70.
Example 2
Input: n = 4, edges = [[1, 2, 5], [3, 4, 7]]
Output: -1
Explanation: no edge joins vertex 1 or 2 to vertex 3 or 4.
Solution

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.

The example graph grown from vertex 1. Tree edges 1-3 (10, 1st), 1-2 (20, 2nd) and 3-4 (40, 3rd) are orange, 2-3 (30) is dashed and 1-4 (50) is unused. A table lists what the heap gives: 1:0, 3:10, 2:20, 2:30 (skipped, 2 is already in) and 4:40, with the total reaching 70.

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], give -1: vertex 1's list is then empty, and the tree never grows past the start.

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[] of {vertex, weight}. The heap here is a PriorityQueue of these pairs, ordered by weight so that the smallest weight comes out first:

Java
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));

The start vertex goes in as {1, 0}, so it joins first and adds nothing to the total. That is the row 1:0 in the picture.

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 has no method to lower the weight of an entry already inside it, so the code simply pushes another entry and lets the smaller one come out first.

The cost is that later entries for the same vertex are out of date. A boolean array inTree marks the vertices that have joined, and an entry whose vertex is already marked is thrown away. Without that check, the run on Example 1 returns 60, not 70. Vertex 2 is counted a second time through the 2:30 entry, the count of joined vertices reaches 4, and the code stops before vertex 4 ever joins.

When to stop

The code stops taking entries from the heap as soon as all n vertices have joined, even if some entries are left. In Example 1, 4:50 is still in the heap at the end, as the note under the table in the picture says. It also stops when the heap runs empty. In Example 2, vertex 1 brings in vertex 2, vertex 2 has no new neighbours to push, and the heap empties with only two of the four vertices joined. Fewer than n joined vertices means the graph is not connected, so the answer is -1.

Java Solution

The method minimumSpanningTreeWeight works in these steps:

  1. First, build the adjacency list adj: one list per vertex from 0 to n, with index 0 unused. A loop over edges adds each edge to the lists of both its ends, as a {neighbour, weight} pair.
  2. Create the array inTree and the min-heap heap, and push {1, 0} for the start vertex. Two counters start at 0: total for the weight so far and added for the vertices that have joined.
  3. A while loop runs as long as the heap is not empty and added is below n. Each time round, poll the entry with the smallest weight into top, and call its vertex u. If inTree[u] is already true, skip the entry.
  4. Otherwise u joins: mark it in inTree, add the entry's weight to total and increase added. Then a loop over u's list pushes {neighbour, weight} for every neighbour not yet in the tree.
  5. After the loop, return total if all n vertices joined, and -1 if not.

The main method runs both examples, a single vertex with no edges, a square of four edges that all weigh 1, and two different edges between vertices 1 and 2.

Java
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:

Output
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} is polled, added reaches 1, and the loop stops.

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, inTree holds one flag per vertex, and the heap can hold up to 2E + 1 entries at once.

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 Kruskal's algorithm. It suits a graph given as a plain list of edges, like the input here.