Skip to lesson

Minimum spanning trees

A minimum spanning tree connects all graph vertices using V - 1 edges at minimal total weight.

What is a Minimum Spanning Tree?

A minimum spanning tree connects all nodes of a weighted graph with the smallest possible total edge weight and no cycles.

A spanning tree is a subgraph connecting all V vertices using exactly V - 1 edges without cycles. A minimum spanning tree (MST) minimises the sum of all chosen edge weights. Spanning trees only exist on connected graphs; disconnected graphs produce spanning forests.

Brute force evaluates all combinations of V - 1 edges to test connectivity. Cayley's formula proves a complete graph contains V^(V - 2) distinct spanning trees. Searching all combinations takes impossible exponential time on even moderate graphs.

Two greedy algorithms solve MST efficiently: Kruskal's algorithm and Prim's algorithm. Both rely on the Cut Property: the lightest edge crossing any cut belongs to the MST.

Kruskal's algorithm with Union-Find

Kruskal's algorithm constructs the MST by processing edges globally in ascending weight order. First, sort all E edges by weight. Initialise a Union-Find structure with V isolated components.

Example 1 · Brute force: test every set of V - 1 edges, exponential time

Main.javaJava
public class Main {    static int find(int[] parent, int i) {        while (parent[i] != i) i = parent[i];        return i;    }
    public static void main(String[] args) {        int n = 4;        int[][] edges = {{0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4}};        int best = Integer.MAX_VALUE;
        for (int mask = 0; mask < (1 << edges.length); mask++) {            if (Integer.bitCount(mask) != n - 1) continue;      // need exactly V - 1 edges            int[] parent = new int[n];            for (int i = 0; i < n; i++) parent[i] = i;            int total = 0;            boolean tree = true;            for (int i = 0; i < edges.length && tree; i++) {                if ((mask & (1 << i)) == 0) continue;                int a = find(parent, edges[i][0]);                int b = find(parent, edges[i][1]);                if (a == b) tree = false;                       // a cycle: not a tree                else { parent[a] = b; total += edges[i][2]; }            }            if (tree) best = Math.min(best, total);        }        System.out.println("MST Total Weight: " + best);    }}
Output
MST Total Weight: 19

What this code does

  • Every subset of edges is a candidate, so the work doubles with each extra edge.
  • A subset with V - 1 edges and no cycle connects every vertex, so it is a spanning tree.
  • Kruskal's greedy choice reaches the same answer after sorting once.

Example 2 · Optimal: Kruskal with Union-Find, O(E log E) time

Main.javaJava
import java.util.*;
public class Main {    static class Edge implements Comparable<Edge> {        int u, v, weight;        Edge(int u, int v, int weight) { this.u = u; this.v = v; this.weight = weight; }        public int compareTo(Edge other) {            return Integer.compare(this.weight, other.weight);        }    }
    static int find(int[] parent, int i) {        if (parent[i] == i) return i;        return parent[i] = find(parent, parent[i]);    }
    static int kruskalMST(int n, List<Edge> edges) {        Collections.sort(edges);        int[] parent = new int[n];        for (int i = 0; i < n; i++) parent[i] = i;
        int totalWeight = 0;        int edgesCount = 0;
        for (Edge e : edges) {            int rootU = find(parent, e.u);            int rootV = find(parent, e.v);            if (rootU != rootV) {                parent[rootU] = rootV;                totalWeight += e.weight;                edgesCount++;                if (edgesCount == n - 1) break;            }        }        return edgesCount == n - 1 ? totalWeight : -1;    }
    public static void main(String[] args) {        List<Edge> edges = new ArrayList<>();        edges.add(new Edge(0, 1, 10));        edges.add(new Edge(0, 2, 6));        edges.add(new Edge(0, 3, 5));        edges.add(new Edge(1, 3, 15));        edges.add(new Edge(2, 3, 4));
        System.out.println("MST Total Weight: " + kruskalMST(4, edges));    }}
Output
MST Total Weight: 19

What this code does

  • Edges sorted by weight: (2,3: 4), (0,3: 5), (0,2: 6), (0,1: 10), (1,3: 15).
  • Accepts (2,3), (0,3), rejects (0,2) as cycle, accepts (0,1).
  • Total minimum spanning tree weight is 4 + 5 + 10 = 19.
  • Sorting once lets the greedy rule add the lightest safe edge each step, so no subset ever has to be tested.

Iterate through the sorted edges one by one. For each edge (u, v, weight), test if find(u) equals find(v). If endpoints share the same component, discard the edge to avoid cycles. Otherwise, accept the edge into the MST and call union(u, v). Stop when exactly V - 1 edges have been added. Sorting takes O(E log E) time and Union-Find takes O(E alpha(V)), totaling O(E log E) time.

Order of execution

Run Kruskal

Tap the steps in the order Kruskal's algorithm runs them.

Prim's algorithm and real-world network design

Prim's algorithm grows a single spanning tree outward from an arbitrary start vertex. Maintain a visited set and a min-heap storing candidate boundary edges. At each step, extract the cheapest edge crossing from visited nodes to unvisited nodes.

Example 3 · Prim's Algorithm in Java

Main.javaJava
import java.util.*;
public class Main {    static class Node {        int to, weight;        Node(int to, int weight) { this.to = to; this.weight = weight; }    }
    static int primMST(int n, List<List<Node>> adj) {        boolean[] vis = new boolean[n];        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
        // [weight, vertex]        pq.offer(new int[]{0, 0});        int totalWeight = 0;        int visitedCount = 0;
        while (!pq.isEmpty()) {            int[] curr = pq.poll();            int w = curr[0];            int u = curr[1];
            if (vis[u]) continue;            vis[u] = true;            totalWeight += w;            visitedCount++;
            for (Node next : adj.get(u)) {                if (!vis[next.to]) {                    pq.offer(new int[]{next.weight, next.to});                }            }        }        return visitedCount == n ? totalWeight : -1;    }
    public static void main(String[] args) {        int n = 4;        List<List<Node>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        adj.get(0).add(new Node(1, 10));        adj.get(1).add(new Node(0, 10));        adj.get(0).add(new Node(2, 6));        adj.get(2).add(new Node(0, 6));        adj.get(0).add(new Node(3, 5));        adj.get(3).add(new Node(0, 5));        adj.get(2).add(new Node(3, 4));        adj.get(3).add(new Node(2, 4));
        System.out.println("Prim MST Weight: " + primMST(n, adj));    }}
Output
Prim MST Weight: 19

What this code does

  • Priority queue extracts the cheapest cut edge at each step.
  • Visited array ensures vertices are incorporated into the tree exactly once.
  • Produces optimal MST weight of 19 in O(E log V) time.

Example 4 · Min Cost to Connect All Points (Manhattan Distance)

Main.javaJava
import java.util.*;
public class Main {    static int minCostConnectPoints(int[][] points) {        int n = points.length;        boolean[] vis = new boolean[n];        int[] minDist = new int[n];        Arrays.fill(minDist, Integer.MAX_VALUE);        minDist[0] = 0;
        int totalCost = 0;
        for (int step = 0; step < n; step++) {            int curr = -1;            for (int i = 0; i < n; i++) {                if (!vis[i] && (curr == -1 || minDist[i] < minDist[curr])) {                    curr = i;                }            }
            vis[curr] = true;            totalCost += minDist[curr];
            for (int next = 0; next < n; next++) {                if (!vis[next]) {                    int dist = Math.abs(points[curr][0] - points[next][0]) +                               Math.abs(points[curr][1] - points[next][1]);                    minDist[next] = Math.min(minDist[next], dist);                }            }        }        return totalCost;    }
    public static void main(String[] args) {        int[][] points = {{0, 0}, {2, 2}, {3, 10}, {5, 2}, {7, 0}};        System.out.println("Min connection cost: " + minCostConnectPoints(points));    }}
Output
Min connection cost: 20

What this code does

  • Models 2D points as a complete graph where edge weight is Manhattan distance.
  • Optimised dense Prim algorithm runs in O(V^2) time without heap overhead.
  • Total minimum wiring cost connecting all 5 points is 20.

Mark the newly discovered neighbour visited. Insert all outgoing edges to unvisited neighbours into the heap. Prim runs in O(E log V) time, excelling on dense graphs where edge counts approach V^2. Civil engineering and telecommunications rely heavily on minimum spanning trees. When laying fiber-optic cables or power lines between cities, MST minimises trenching costs. It guarantees universal connectivity at the lowest possible total installation expense.

Next step

Check your understanding

10 quick questions