Kodewick
Start learning →
Minimum spanning trees: Prim and Kruskal33 / 50

Minimum spanning trees: Prim and Kruskal

Lesson 33 of 50 · Part 6 · Graphs · about 18 minutes

A minimum spanning tree (MST) joins all n vertices with n − 1 edges of the smallest total weight: Prim grows it from one vertex, joining the vertex nearest the tree each time, and Kruskal takes edges shortest first, skipping any that union-find shows would make a cycle.

Six villages need internet, and laying fibre between any two of them costs a different amount. Not every pair needs a direct line; it's enough for all the villages to be joined up. What's the cheapest plan? Joining n villages takes at least n − 1 lines; one more makes a cycle, and dropping the dearest line on that cycle leaves everything joined and costs less. So what's wanted is: n − 1 edges, joining every vertex, with the smallest total weight. That's a minimum spanning tree (MST). Power grids, pipelines, circuit board wiring and clustering algorithms all use it.

Prim: grow out from one vertex

Prim works like Dijkstra: a tree starts at one vertex, and each time the vertex nearest the tree is joined on, with the edge that reaches it. lowcost[v] holds "the shortest edge from v to any vertex in the tree":

  1. The start goes in the tree, and its edges set up lowcost.
  2. n − 1 times: pick the v not in the tree with the smallest lowcost, and join it and that edge to the tree; then use v's edges to update the other vertices' lowcost (only when smaller).

The one difference from Dijkstra: Dijkstra compares dist[u] + w (distance to the start), Prim compares just w (distance to the tree).

Prim from 0. The number on a vertex is its lowcost: its shortest edge to the tree so far; green vertices are in the tree, thick lines are edges taken into the tree

Each round scans lowcost once for the smallest and once more to update, n rounds: O(n²), whatever the number of edges. So Prim suits dense graphs.

Choose one

Edges A–B 3, A–C 1, B–C 2, B–D 4, C–D 5, D–E 2, C–E 6. Running Prim from A, in what order do edges join the tree?

Choose one

Prim with the lowcost array is O(n²). What kind of graph does it suit best?

Exercise 1

Write Prim

Fill in each round of Prim: among the vertices not in the tree, pick v with the smallest lowcost, print from[v]-v, add the weight, and mark it in the tree; then use v's edges to update lowcost and from.

It should print
0-2 2-4 4-3 2-1 3-5 
18
exercise1.c
1#include <stdio.h>2 3#define N 64#define INF 10000000005 6int w[N][N];7 8void add(int u, int v, int c) { w[u][v] = w[v][u] = c; }9 10int main(void) {11    for (int i = 0; i < N; i++)12        for (int j = 0; j < N; j++)13            w[i][j] = INF;14    add(0, 1, 6); add(0, 2, 1); add(1, 2, 4); add(1, 3, 5); add(2, 3, 7);15    add(2, 4, 3); add(3, 4, 2); add(3, 5, 8); add(4, 5, 9);16    int in[N] = {0}, lowcost[N], from[N], total = 0;17    in[0] = 1;18    for (int i = 0; i < N; i++) {19        lowcost[i] = w[0][i];20        from[i] = 0;21    }22    for (int k = 1; k < N; k++) {23        int v = -1;24        // 1. among those not in the tree, find v with the smallest lowcost25        // 2. print from[v]-v, add lowcost[v] to total, in[v] = 126        // 3. for each j not in the tree: if w[v][j] < lowcost[j], update lowcost[j] and from[j]27    }28    printf("\n%d\n", total);29    return 0;30}
Output
Press Run or Ctrl+Enter

Kruskal: shortest edges first, unless they make a cycle

Kruskal sees it another way: never mind where the tree grows; sort all the edges from smallest to largest and go through them: if the edge's two ends aren't connected yet, take it; if they are, taking it would make a cycle, so skip it. Stop after n − 1 edges.

The edges sorted: 0–2 (1), 3–4 (2), 2–4 (3), 1–2 (4), 1–3 (5), 0–1 (6), 2–3 (7), 3–5 (8), 4–5 (9).

Kruskal: edges looked at shortest first. At the start each vertex is a piece on its own, and each edge taken merges two pieces into one

Sorting is O(e log e), and checking each edge's ends is nearly O(1) afterwards (thanks to union-find, the last level of this lesson), so Kruskal is O(e log e) and suits sparse graphs.

What if you skip the cycle check and just take the n − 1 shortest edges?

main.c
1#include <stdio.h>2 3int main(void) {4    // the 9 edges, already sorted by weight5    int u[] = {0, 3, 2, 1, 1, 0, 2, 3, 4};6    int v[] = {2, 4, 4, 2, 3, 1, 3, 5, 5};7    int w[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};8    int total = 0, touches5 = 0;9    for (int i = 0; i < 5; i++) {            // just take the 5 shortest10        printf("%d-%d(%d) ", u[i], v[i], w[i]);11        total += w[i];12        if (u[i] == 5 || v[i] == 5) touches5 = 1;13    }14    printf("\ntotal %d, even less than 18\n", total);15    printf("is vertex 5 joined on? %s\n", touches5 ? "yes" : "no");16    return 0;17}
Output
0-2(1) 3-4(2) 2-4(3) 1-2(4) 1-3(5) 
total 15, even less than 18
is vertex 5 joined on? no

A total of 15 looks cheaper, but 1–2, 2–4, 3–4 and 1–3 go round in a cycle, so one of the 5 edges is wasted, and vertex 5 isn't joined on at all. Every edge needs the question "are its ends connected already?" first.

Choose one

The same graph: Edges A–B 3, A–C 1, B–C 2, B–D 4, C–D 5, D–E 2, C–E 6. In what order does Kruskal pick edges?

Choose one

Same graph again. Which is the first edge Kruskal skips?

Union-find: are two vertices connected?

Kruskal keeps asking "are u and v in the same piece?" and then "merge the two pieces". Union-find does exactly that: each piece is a tree stored in a parent[] array, each vertex pointing to its parent and each root pointing to itself.

  • find(x): follow parent up to the root. Two vertices with the same root are in the same piece.
  • union(a, b): hang a's root under b's root.

The trees can grow tall as things get hung on them, so find has a long way to go. Path compression: once find reaches the root, point every vertex it passed on the way straight at the root, so next time it's one step.

012345parent012345

How the parent array changes through the whole Kruskal run. union(a, b) is parent[find(a)] = find(b)
main.c
1#include <stdio.h>2#include <stdlib.h>3 4#define N 65 6typedef struct { int u, v, w; } Edge;7 8int parent[N];9 10int find(int x) {                  // find the root, pointing everything on the way straight at it11    if (parent[x] != x)12        parent[x] = find(parent[x]);13    return parent[x];14}15 16int cmp(const void *a, const void *b) {17    return ((const Edge *)a)->w - ((const Edge *)b)->w;18}19 20int main(void) {21    Edge e[] = {{0, 1, 6}, {0, 2, 1}, {1, 2, 4}, {1, 3, 5}, {2, 3, 7},22                {2, 4, 3}, {3, 4, 2}, {3, 5, 8}, {4, 5, 9}};23    int m = sizeof e / sizeof e[0];24    qsort(e, m, sizeof(Edge), cmp);           // smallest weight first25    for (int i = 0; i < N; i++) parent[i] = i;26    int picked = 0, total = 0;27    for (int i = 0; i < m && picked < N - 1; i++) {28        int a = find(e[i].u), b = find(e[i].v);29        if (a == b) {30            printf("skip %d-%d(%d): it makes a cycle\n", e[i].u, e[i].v, e[i].w);31            continue;32        }33        parent[a] = b;                         // two pieces become one34        picked++;35        total += e[i].w;36        printf("take %d-%d(%d)\n", e[i].u, e[i].v, e[i].w);37    }38    printf("total %d\nparent: ", total);39    for (int i = 0; i < N; i++) printf("%d ", parent[i]);40    printf("\n");41    return 0;42}
Output
take 0-2(1)
take 3-4(2)
take 2-4(3)
take 1-2(4)
skip 1-3(5): it makes a cycle
skip 0-1(6): it makes a cycle
skip 2-3(7): it makes a cycle
take 3-5(8)
total 18
parent: 4 4 4 4 5 5 

With path compression (plus "union by rank": hang the shorter tree under the taller), each find is nearly constant time on average.

Guess the outputA wrong guess is fine

Edges 1–3 (5), 0–2 (3), 0–1 (1), 2–3 (4), 1–2 (2). What's the minimum spanning tree's total weight?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct { int u, v, w; } Edge;5 6int parent[4];7 8int find(int x) {9    if (parent[x] != x) parent[x] = find(parent[x]);10    return parent[x];11}12 13int cmp(const void *a, const void *b) {14    return ((const Edge *)a)->w - ((const Edge *)b)->w;15}16 17int main(void) {18    Edge e[] = {{1, 3, 5}, {0, 2, 3}, {0, 1, 1}, {2, 3, 4}, {1, 2, 2}};19    qsort(e, 5, sizeof(Edge), cmp);20    for (int i = 0; i < 4; i++) parent[i] = i;21    int total = 0;22    for (int i = 0; i < 5; i++) {23        int a = find(e[i].u), b = find(e[i].v);24        if (a != b) {25            parent[a] = b;26            total += e[i].w;27        }28    }29    printf("%d\n", total);30    return 0;31}
Choose one

6 vertices start as roots (parent[i] = i). Do union(0, 1), union(2, 3), union(1, 3) in turn, where union(a, b) is parent[find(a)] = find(b). What is the parent array now?

Fill inTap one to fill a blank; tap a blank to take it back

What should Kruskal do with an edge whose ends are already connected? Pick one so the program prints the minimum spanning tree's total, 18.

1#include <stdio.h>2#include <stdlib.h>3 4#define N 65 6typedef struct { int u, v, w; } Edge;7 8int parent[N];9 10int find(int x) {11    if (parent[x] != x) parent[x] = find(parent[x]);12    return parent[x];13}14 15int cmp(const void *a, const void *b) {16    return ((const Edge *)a)->w - ((const Edge *)b)->w;17}18 19int main(void) {20    Edge e[] = {{0, 1, 6}, {0, 2, 1}, {1, 2, 4}, {1, 3, 5}, {2, 3, 7},21                {2, 4, 3}, {3, 4, 2}, {3, 5, 8}, {4, 5, 9}};22    qsort(e, 9, sizeof(Edge), cmp);23    for (int i = 0; i < N; i++) parent[i] = i;24    int total = 0;25    for (int i = 0; i < 9; i++) {26        int a = find(e[i].u), b = find(e[i].v);27        if (a == b) ;28        parent[a] = b;29        total += e[i].w;30    }31    printf("%d\n", total);32    return 0;33}
Exercise 2

Counting pieces with union-find

Fill in find (with path compression). After the program's unions, it counts the roots (parent[i] == i), which is the number of pieces.

It should print
3 pieces; 0 and 2 connected
exercise2.c
1#include <stdio.h>2 3#define N 84 5int parent[N];6 7int find(int x) {8    // if parent[x] isn't x itself, parent[x] = find(parent[x]); finally return parent[x]9    return x;10}11 12void unite(int a, int b) { parent[find(a)] = find(b); }13 14int main(void) {15    for (int i = 0; i < N; i++) parent[i] = i;16    unite(0, 1); unite(2, 3); unite(1, 3); unite(5, 6); unite(6, 7);17    int blocks = 0;18    for (int i = 0; i < N; i++)19        if (parent[i] == i) blocks++;20    printf("%d pieces; 0 and 2 %s\n", blocks, find(0) == find(2) ? "connected" : "not connected");21    return 0;22}
Output
Press Run or Ctrl+Enter

Prim or Kruskal?

Both algorithms find a minimum spanning tree. Exams and interviews like to ask when to use which, along with a few facts that are easy to mix up.

PrimKruskal
How it growsone tree grows from one vertexmany pieces, merged as edges are taken
Each stepjoin the vertex nearest the treethe next shortest edge, unless it makes a cycle
Needsthe lowcost array (or a heap)sorting + union-find
TimeO(n²); heap O(e log n)O(e log e)
Suitsdense graphssparse graphs

When all edge weights differ, the minimum spanning tree is unique and both algorithms pick the same edges; with equal weights there may be several, all with the same total.

In exams: "find the minimum spanning tree with Prim (from some vertex) / Kruskal, giving the order edges are chosen": Prim's order depends on the start, Kruskal's is the edges from smallest weight up (skipping the ones that make cycles). Common true/false questions: "is the minimum spanning tree unique?" (yes when all weights differ), "is the path between two vertices in a minimum spanning tree a shortest path?" (no, that's Dijkstra's job).

Choose one

In a connected graph, all the edge weights are different. How many minimum spanning trees does it have?

Choose one

The triangle A–B 2, B–C 2, A–C 3 has minimum spanning tree A–B and B–C. In the tree, the path from A to C is 4 long. What's the shortest path from A to C in the graph?

Summary

Take-away

Minimum spanning tree: n − 1 edges, connected, smallest total

  • Prim: grow from one vertex, joining the one nearest the tree; O(n²), dense graphs
  • Kruskal: edges shortest first, taken only if the ends aren't connected; O(e log e), sparse graphs
  • Union-find: find goes to the root, union hangs one root on another, path compression
  • Without the cycle check you get cycles and miss vertices
1int find(int x) {2    if (parent[x] != x)3        parent[x] = find(parent[x]);4    return parent[x];5}