Graph - Kruskal's Minimum Spanning Tree (MST)

Connect every vertex of a weighted graph at the smallest total cost by taking the cheapest edges that do not close a cycle.

Take a connected, undirected graph whose n vertices are numbered 1 to n, with each weighted edge written as {u, v, weight}. Choose a set of edges that still connects every vertex and has the smallest possible total weight. Return the chosen edges and their total weight.

Example 1
Input: n = 5, edges = [[1, 2, 4], [1, 3, 1], [2, 3, 3], [2, 4, 2], [3, 4, 7], [3, 5, 6], [4, 5, 5]]
Output: 1-3 (1), 2-4 (2), 2-3 (3), 4-5 (5), total weight 11
Example 2
Input: n = 4, edges = [[1, 2, 20], [1, 3, 10], [2, 3, 30], [3, 4, 40], [1, 4, 50]]
Output: 1-3 (10), 1-2 (20), 3-4 (40), total weight 70
Solution

The Idea

Picture five villages, numbered 1 to 5, that want to be linked by roads. Not every pair can be linked, and each possible road has a building cost. Example 1 is exactly that: each vertex is a village, each edge a possible road, and its weight the cost. Which roads should be built so that people can drive between any two villages, for the least money?

Some roads are clearly wasted. Suppose roads 1-3 and 2-3 are built. Then 1 can already reach 2 through 3, and a road 1-2 would only close a ring 1, 2, 3 and back to 1. Such a ring is called a cycle, and the cheapest answer never contains one.

So the answer reaches every village without any cycle. A set of edges like that is called a spanning tree. Example 1 has more than one, and the one whose weights add up to the least is called its minimum spanning tree. How many roads does it have? At the start the five villages are five separate pieces. Each useful road joins two pieces into one, so it takes exactly 4 roads to get down to a single piece, one fewer than the number of villages.

Which 4, though? Kruskal's algorithm answers with a short rule: look at the edges from cheapest to most expensive, and take each one unless it closes a cycle with the edges taken so far. The picture shows the rule on Example 1.

The Example 1 graph with its seven edges, and the edges listed cheapest first. 1-3 (1), 2-4 (2) and 2-3 (3) are taken, 1-2 (4) is skipped because 1 and 2 are already in one group, 4-5 (5) is taken, and 3-5 (6) and 3-4 (7) are never looked at.

While the rule runs, the vertices linked so far form groups, and at the start each vertex is a group of its own. Start at the top of the list headed "edges, cheapest first". The row 1-3 (1) is the edge between 1 and 3 with weight 1. It joins the separate groups {1} and {3}, so it is taken and drawn in orange. So is 2-4 (2). Now there are three groups: {1, 3}, {2, 4} and {5}. Next, 2-3 (3) joins {1, 3} and {2, 4} into one group, and it is taken too.

The row labelled 1-2 (4) is where the rule matters. Vertices 1 and 2 are already in one group, through 3, so this edge would close a cycle. It is skipped, and the graph on the left draws it as a dashed blue line.

Then 4-5 (5) brings in vertex 5. That makes 4 edges, every vertex is joined, and the rows marked "never looked at" stay untouched. The four orange edges cost 1 + 2 + 3 + 5 = 11, the total weight in Example 1.

Solution Approach

Four decisions turn that rule into code: the order in which the edges are looked at, how to tell that an edge closes a cycle, how to join two groups, and when to stop.

Looking at the cheapest edge first

Why sort the edges at all? Without any order, a program could try every set of 4 edges, keep the sets that connect all five villages, and pick the cheapest. The number of such sets grows very fast as graphs get bigger. Kruskal looks at each edge at most once, in sorted order, instead.

The order is what makes that work. Taking Example 1's edges in the order the input lists them, with the same cycle check, gives 1-2 (4), 1-3 (1), 2-4 (2) and 3-5 (6), a total of 13 instead of 11. Edge 1-2 came first and was taken before the cheaper 2-3 (3) had its chance.

Why is the cheapest choice safe, then? Go back to the moment 2-3 (3) was taken. The group {1, 3} had to be connected to the rest of the graph by some edge, and the edges leaving it are 1-2 (4), 2-3 (3), 3-5 (6) and 3-4 (7). Suppose a tree left 2-3 out. Adding 2-3 to it would close a cycle, and that cycle leaves {1, 3} through one of the other three edges as well. Removing that edge keeps every vertex connected and costs no more, because 2-3 is the cheapest of the four. Taking the cheapest edge that joins two groups, without looking ahead, is a greedy choice, and this swap argument is why it never loses here.

Telling that an edge closes a cycle

How does the code know that 1 and 2 are already in one group? It could search the edges taken so far, starting at 1, to see whether 2 can be reached. That repeats a search for every edge.

A cheaper record of the groups works instead. Each group has one vertex in charge of it, called its root. An array parent gives every vertex a link to another vertex in its group, and following the links always ends at the root, whose link points to itself. At the start, parent[v] = v for every vertex, so each vertex is a group of its own.

In Example 1, just before the edge 1-2 (4), the array holds 3, 4, 3, 3, 5 for vertices 1 to 5. From 1 the link leads to 3, and 3 points to itself, so the root of 1 is 3. From 2 the links go to 4 and then to 3, so the root of 2 is also 3. The roots are equal, so 1 and 2 are in one group and the edge is skipped.

Following the links to the root is the job of a method called find. On the way up, it also points each vertex it passes at the vertex two steps higher, which is called path halving. Looking up 2 for the edge 1-2 changed parent[2] from 4 to 3, so the next lookup of 2 takes one step instead of two. The parent array together with find and a way to join groups is known as union-find.

Joining two groups at their roots

Once find returns two different roots, how are the groups joined? One assignment does it: the first root gets the second root as its parent. In Example 1, the edge 2-3 (3) found the roots 4 and 3, so parent[4] became 3, and every vertex of {2, 4} now leads to 3.

The link has to go between the roots, not between the two ends of the edge. A version that links the edge's first end straight to its second end looks almost the same, but it can tear a group apart. On Example 2, the edge 1-2 (20) found the roots 3 and 2. Setting the parent of vertex 1 to 2 threw away its link to 3, so 3 was left in a group of its own.

Then 2-3 (30) looked safe and was taken, closing the cycle 1, 2, 3. That broken run returned 1-3 (10), 1-2 (20) and 2-3 (30), a total of 60, which is less than 70 only because vertex 4 is never connected.

When to stop

When can Kruskal stop looking at edges? Each taken edge joins two groups into one, so after n - 1 taken edges a single group is left and the remaining edges cannot add anything. In Example 1 that happens after 5 of the 7 edges, which is why 3-5 (6) and 3-4 (7) are never looked at.

If the graph is not connected, the edges run out first and fewer than n - 1 edges are chosen. The method then returns what it found, and the caller can compare the count with n - 1 to see that no spanning tree exists.

Java Solution

The method minimumSpanningTree uses a helper, find(parent, x), which climbs the parent links from vertex x to the root of its group, halving the path on the way. The method works in these steps:

  1. First, copy the edge array with edges.clone() into sorted, and sort the copy by weight with Arrays.sort and Comparator.comparingInt(edge -> edge[2]). The caller's array keeps its order.
  2. Create the array parent with n + 1 slots, and set each vertex's slot to the vertex itself. Vertices are numbered from 1, so slot 0 is never used.
  3. Create the list tree for the chosen edges, then loop over sorted one edge at a time. At the top of the loop, stop once tree holds n - 1 edges.
  4. Call find on both ends of the edge to get root1 and root2. If they are equal, the edge would close a cycle, so move on to the next edge.
  5. Otherwise join the groups with parent[root1] = root2 and add the edge to tree.
  6. When the loop ends, return tree.

A small method, show, prints the chosen edges and their total, or the words "not connected". Besides the two examples, main tries three edge cases: a graph split into two pieces, a lone vertex with no edges, and vertices 1 and 2 joined by two edges of different weight. Last, it prints Example 1's edge array again, to show its order.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Kruskal {

    // Vertices are 1..n, edges[i] = {u, v, weight}. Returns the edges of a minimum spanning tree.
    public static List<int[]> minimumSpanningTree(int n, int[][] edges) {
        int[][] sorted = edges.clone();
        Arrays.sort(sorted, Comparator.comparingInt(edge -> edge[2]));   // cheapest edge first

        int[] parent = new int[n + 1];
        for (int v = 0; v <= n; v++) {
            parent[v] = v;                     // every vertex starts as its own group
        }
        List<int[]> tree = new ArrayList<>();
        for (int[] edge : sorted) {
            if (tree.size() == n - 1) {
                break;                         // n - 1 edges already connect all n vertices
            }
            int root1 = find(parent, edge[0]);
            int root2 = find(parent, edge[1]);
            if (root1 == root2) {
                continue;                      // same group: this edge would close a cycle
            }
            parent[root1] = root2;             // join the two groups
            tree.add(edge);
        }
        return tree;
    }

    // Follows parent links up to the group's root, halving the path on the way.
    private static int find(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }

    static void show(int n, int[][] edges) {
        List<int[]> tree = minimumSpanningTree(n, edges);
        StringBuilder sb = new StringBuilder();
        int total = 0;
        for (int[] edge : tree) {
            sb.append(edge[0]).append('-').append(edge[1]);
            sb.append(" (").append(edge[2]).append("), ");
            total += edge[2];
        }
        if (tree.size() == n - 1) {
            System.out.println(sb + "total " + total);
        } else {
            System.out.println(sb + "not connected: " + tree.size() + " of " + (n - 1) + " edges");
        }
    }

    public static void main(String[] args) {
        int[][] example1 = {{1, 2, 4}, {1, 3, 1}, {2, 3, 3}, {2, 4, 2},
                            {3, 4, 7}, {3, 5, 6}, {4, 5, 5}};
        int[][] example2 = {{1, 2, 20}, {1, 3, 10}, {2, 3, 30}, {3, 4, 40}, {1, 4, 50}};
        show(5, example1);
        show(4, example2);
        show(4, new int[][] {{1, 2, 5}, {3, 4, 2}});              // two separate pieces
        show(1, new int[][] {});                                  // one vertex, no edges
        show(3, new int[][] {{1, 2, 3}, {1, 2, 1}, {2, 3, 2}});   // two edges between 1 and 2
        System.out.println(Arrays.deepToString(example1));        // input order unchanged
    }
}

Running it prints:

Output
1-3 (1), 2-4 (2), 2-3 (3), 4-5 (5), total 11
1-3 (10), 1-2 (20), 3-4 (40), total 70
3-4 (2), 1-2 (5), not connected: 2 of 3 edges
total 0
1-2 (1), 2-3 (2), total 3
[[1, 2, 4], [1, 3, 1], [2, 3, 3], [2, 4, 2], [3, 4, 7], [3, 5, 6], [4, 5, 5]]

The line ending in "total 11" lists the four orange edges from the picture, in the order they were taken. In Example 2, on the next line, 2-3 (30) is missing: by the time it came up, 2 and 3 were already joined through 1, and 3-4 (40) completed the tree.

The graph in two pieces gives "not connected: 2 of 3 edges". Both of its edges were taken, 3-4 (2) before 1-2 (5), but no edge links {1, 2} with {3, 4}. A single vertex needs no edges at all, so its line reads "total 0" and the loop stops before looking at anything.

Look at "1-2 (1), 2-3 (2), total 3". The input had two edges between 1 and 2, with weights 3 and 1. Sorting put the cheaper one first, and the copy with weight 3 came last, after the tree already had its 2 edges. The last line shows Example 1's edges still in their input order, because only the copy was sorted.

Complexity

The cost is one sort of the edges plus two find calls for each edge looked at, for a graph with V vertices (n in the code) and E edges.

  • Time: O(E log E), because sorting the E edges outweighs the rest of the work. The loop makes at most 2E calls to find, and with path halving they average O(log V) each, which is no more than O(log E) in a connected graph.
  • Space: O(V + E), because sorted holds a reference to each of the E edges, parent has V + 1 slots, and tree keeps at most V - 1 edges.

Prim's Algorithm builds the same kind of tree another way: it grows the tree outward from one vertex instead of sorting every edge.