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 nn{u, v, weight}
Example 1
Output: 1-3 (1), 2-4 (2), 2-3 (3), 4-5 (5), total weight 11
Example 2
Output: 1-3 (10), 1-2 (20), 3-4 (40), total weight 70
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.
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 parentparent[v] = v
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 findparent[2]find
Joining two groups at their roots
Once findparent[4]
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
If the graph is not connected, the edges run out first and fewer than n - 1n - 1
Java Solution
The method minimumSpanningTreefind(parent, x)x
- First, copy the edge array with
intoedges.clone() , and sort the copy by weight withsorted andArrays.sort . The caller's array keeps its order.Comparator.comparingInt(edge -> edge[2]) - Create the array
withparent slots, and set each vertex's slot to the vertex itself. Vertices are numbered from 1, so slot 0 is never used.n + 1 - Create the list
for the chosen edges, then loop overtree onesorted at a time. At the top of the loop, stop onceedge holdstree edges.n - 1 - Call
on both ends of the edge to getfind androot1 . If they are equal, the edge would close a cycle, so move on to the next edge.root2 - Otherwise join the groups with
and add the edge toparent[root1] = root2 .tree - When the loop ends, return
.tree
A small method, showmain
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:
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 findn
- Time: O(E log E), because sorting the E edges outweighs the rest of the work. The loop makes at most 2E calls to
, and with path halving they average O(log V) each, which is no more than O(log E) in a connected graph.find - Space: O(V + E), because
holds a reference to each of the E edges,sorted has V + 1 slots, andparent keeps at most V - 1 edges.tree