Find the MST of the graph with edges P–Q 4, P–R 1, Q–R 3, Q–S 2, R–S 5, S–T 7, R–T 6 using Kruskal's algorithm.
A minimum spanning tree connects all vertices of a connected, weighted, undirected graph using V − 1 edges of least total weight. Prim grows one tree from a start vertex; Kruskal adds the cheapest safe edges using union–find — both greedy.
A spanning tree of a connected undirected graph G is a subgraph that includes every vertex of G and is a tree — connected and acyclic. With V vertices it always has exactly V − 1 edges: one fewer and it would be disconnected, one more and it would contain a cycle. Adding any non-tree edge creates exactly one cycle; removing any tree edge splits the tree into two pieces. Every connected graph has at least one spanning tree (BFS and DFS trees are examples), and usually very many.
In a weighted graph, a minimum spanning tree (MST) — strictly, a minimum-weight spanning tree — is a spanning tree whose total edge weight is as small as possible. It answers ‘what is the cheapest way to connect everything?’ for cable, pipeline, road and electrical-grid design, and appears inside other algorithms: single-linkage clustering, approximate travelling-salesman tours (the 2-approximation via an MST walk) and image segmentation.
The running example: vertices A–F with edges A–C 1, C–D 2, A–D 3, B–C 4, A–B 5, D–E 6, B–E 7, E–F 8, D–F 9. This graph has 64 different spanning trees; exactly one of them — because all weights are distinct — has the minimum weight, 21.
Why greedy is safe. Both algorithms repeatedly add the cheapest edge that crosses some cut without creating a cycle — Prim's cut separates the growing tree from the remaining vertices; Kruskal's separates the two components the edge joins. The cut property guarantees each such edge belongs to an MST, so the choices never have to be undone. In the example, the cycle A–C–D has heaviest edge A–D (3) and the cycle D–E–F has heaviest edge D–F (9), so neither can be in the MST; the cut {F} versus the rest is crossed by E–F (8) and D–F (9), so E–F must be in it.
Prim's algorithm was first found by Vojtěch Jarník (1930), rediscovered by Robert Prim (1957) and again by Dijkstra (1959), so it is also called the Jarník or Prim–Jarník algorithm. It grows a single tree outward from an arbitrary start vertex. Every vertex v outside the tree carries a key: the weight of the cheapest edge joining v to the tree so far. At each step the vertex with the smallest key joins the tree, and its neighbours' keys are lowered where possible.
| Step | Vertex added (edge) | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|
| 1 | A (start) | ✓ | 5 | 1 | 3 | ∞ | ∞ |
| 2 | C (A–C, 1) | ✓ | 4 | ✓ | 2 | ∞ | ∞ |
| 3 | D (C–D, 2) | ✓ | 4 | ✓ | ✓ | 6 | 9 |
| 4 | B (C–B, 4) | ✓ | ✓ | ✓ | ✓ | 6 | 9 |
| 5 | E (D–E, 6) | ✓ | ✓ | ✓ | ✓ | ✓ | 8 |
| 6 | F (E–F, 8) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
MST edges in the order Prim adds them: A–C (1), C–D (2), C–B (4), D–E (6), E–F (8); total 21. Note how B's key fell from 5 to 4 when C joined, and F's from 9 to 8 when E joined — that is the ‘update keys’ step at work.
#include <stdio.h>
#include <limits.h>
#define V 6
const char *name = "ABCDEF";
int main(void) {
int g[V][V] = {{0}}; /* 0 = no edge */
int e[][3] = {{0,2,1}, {2,3,2}, {0,3,3}, {1,2,4}, {0,1,5},
{3,4,6}, {1,4,7}, {4,5,8}, {3,5,9}};
for (int i = 0; i < 9; i++) g[e[i][0]][e[i][1]] = g[e[i][1]][e[i][0]] = e[i][2];
int key[V], parent[V], inTree[V], total = 0;
for (int v = 0; v < V; v++) { key[v] = INT_MAX; parent[v] = -1; inTree[v] = 0; }
key[0] = 0; /* start at A */
for (int round = 0; round < V; round++) {
int u = -1;
for (int v = 0; v < V; v++) /* cheapest vertex outside the tree */
if (!inTree[v] && (u == -1 || key[v] < key[u])) u = v;
inTree[u] = 1;
if (parent[u] != -1) {
printf("add %c-%c (%d)\n", name[parent[u]], name[u], key[u]);
total += key[u];
}
for (int v = 0; v < V; v++) /* lower the neighbours' keys */
if (g[u][v] && !inTree[v] && g[u][v] < key[v]) { key[v] = g[u][v]; parent[v] = u; }
}
printf("total weight = %d\n", total); /* 21 */
return 0;
}Cost. With an adjacency matrix and a linear scan for the minimum key, Prim runs in O(V²) — the best choice for dense graphs. With adjacency lists and a binary heap it is O((V + E) log V) = O(E log V) for a connected graph; a Fibonacci heap gives O(E + V log V). Prim looks almost exactly like Dijkstra; the only difference is the key: Prim uses the weight of the single edge to the tree, Dijkstra the total distance from the source.
Joseph Kruskal published his algorithm in 1956. It thinks in edges rather than vertices: start with a forest of V single-vertex trees, consider the edges in increasing order of weight, and accept an edge if and only if its endpoints lie in different trees (so it cannot form a cycle). Each accepted edge merges two trees; after V − 1 acceptances one tree remains — the MST.
| Edge | Weight | Endpoints already connected? | Action | Components afterwards |
|---|---|---|---|---|
| A–C | 1 | no | accept | {A, C} {B} {D} {E} {F} |
| C–D | 2 | no | accept | {A, C, D} {B} {E} {F} |
| A–D | 3 | yes (A–C–D) | reject — would close a cycle | unchanged |
| B–C | 4 | no | accept | {A, B, C, D} {E} {F} |
| A–B | 5 | yes | reject | unchanged |
| D–E | 6 | no | accept | {A, B, C, D, E} {F} |
| B–E | 7 | yes | reject | unchanged |
| E–F | 8 | no | accept — 5 = V − 1 edges, stop | {A, B, C, D, E, F} |
| D–F | 9 | — | never examined | — |
Kruskal accepts A–C, C–D, B–C, D–E and E–F — the same tree that Prim found, total 21, as it must be because the weights are distinct. Here Kruskal happened to accept the edges in the same order Prim added them; starting Prim from F instead adds them in the order 8, 6, 2, 1, 4, whereas Kruskal's order is always sorted by weight.
Union–find (disjoint-set union). The cycle test needs to know quickly whether two vertices are in the same tree. Keep each tree as a set with a representative: find(x) returns x's representative and union(a, b) merges two sets. With union by rank (attach the shorter tree under the taller) and path compression (make every node on a find path point straight at the root), any sequence of operations costs O(α(n)) amortised each — α is the inverse Ackermann function, below 5 for any practical n.
#include <stdio.h>
#include <stdlib.h>
#define V 6
#define E 9
struct Edge { int u, v, w; };
const char *name = "ABCDEF";
int parent[V], rnk[V];
int find(int x) { /* path compression */
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
int unite(int a, int b) { /* union by rank; 0 if same set */
a = find(a); b = find(b);
if (a == b) return 0;
if (rnk[a] < rnk[b]) { int t = a; a = b; b = t; }
parent[b] = a;
if (rnk[a] == rnk[b]) rnk[a]++;
return 1;
}
int byWeight(const void *x, const void *y) {
return ((const struct Edge *)x)->w - ((const struct Edge *)y)->w;
}
int main(void) {
struct Edge e[E] = {{0,1,5}, {0,2,1}, {0,3,3}, {1,2,4}, {1,4,7},
{2,3,2}, {3,4,6}, {3,5,9}, {4,5,8}};
qsort(e, E, sizeof e[0], byWeight); /* O(E log E) */
for (int i = 0; i < V; i++) { parent[i] = i; rnk[i] = 0; }
int taken = 0, total = 0;
for (int i = 0; i < E && taken < V - 1; i++) {
if (unite(e[i].u, e[i].v)) {
printf("accept %c-%c (%d)\n", name[e[i].u], name[e[i].v], e[i].w);
total += e[i].w;
taken++;
} else {
printf("reject %c-%c (%d)\n", name[e[i].u], name[e[i].v], e[i].w);
}
}
printf("total weight = %d\n", total); /* 21 */
return 0;
}Cost. Sorting dominates: O(E log E), which equals O(E log V) because E < V² means log E < 2 log V. The union–find work adds only O(E α(V)). If the edges arrive already sorted, or weights are small integers that can be counting-sorted, Kruskal is almost linear.
| Aspect | Prim | Kruskal |
|---|---|---|
| Approach | vertex-based: grow one tree from a start vertex | edge-based: merge a forest, cheapest edge first |
| Needs a start vertex? | yes (any vertex gives a valid MST) | no |
| Partial result | always one connected tree | a forest that becomes connected only at the end |
| Main data structure | priority queue of vertex keys | sorted edge list + union–find |
| Time | O(V²) with a matrix; O(E log V) with a binary heap | O(E log E) = O(E log V) |
| Best for | dense graphs (adjacency matrix) | sparse graphs (edge list) |
| Disconnected graph | spans only the start vertex's component | gives a minimum spanning forest |
| Design technique | greedy | greedy |
Two other MST algorithms complete the picture. Borůvka's algorithm (Otakar Borůvka, 1926 — the oldest, designed for the Moravian electricity network) lets every component pick its cheapest outgoing edge simultaneously, halving the number of components each round: O(E log V), and easy to parallelise. The reverse-delete algorithm starts from the whole graph and deletes edges from heaviest to lightest unless deletion would disconnect the graph.
How many spanning trees does a graph have? For the complete graph the answer is Cayley's formula (Arthur Cayley, 1889): Kₙ has nⁿ⁻² spanning trees — equivalently, there are nⁿ⁻² different labelled trees on n vertices. For an arbitrary graph, Kirchhoff's matrix-tree theorem (1847) gives the count as any cofactor of the Laplacian matrix L = D − A (degree matrix minus adjacency matrix).
| Graph | Formula | Values |
|---|---|---|
| Complete graph Kₙ | nⁿ⁻² | K₃ = 3, K₄ = 16, K₅ = 125, K₆ = 1296 |
| Cycle Cₙ | n (remove any one edge) | C₇ = 7 |
| Complete bipartite K_{m,n} | mⁿ⁻¹ · nᵐ⁻¹ | K₂,₃ = 2² × 3¹ = 12 |
| K₄ with one edge removed | 16 − 8 (each edge of K₄ lies in 8 of its 16 spanning trees) | 8 |
| A tree | 1 (it is its own only spanning tree) | 1 |
Effect of changing weights. Every spanning tree has exactly V − 1 edges, so adding the same constant c to every edge raises every spanning tree's weight by (V − 1)·c and leaves the same tree minimal. Any change that preserves the order of the weights — doubling them, squaring positive weights — also keeps the MST. Shortest paths, by contrast, can change when a constant is added, because paths with more edges are penalised more.
Try the problem first, then reveal the working one step at a time.
Find the MST of the graph with edges P–Q 4, P–R 1, Q–R 3, Q–S 2, R–S 5, S–T 7, R–T 6 using Kruskal's algorithm.
Vertices 1–5 with edges 1–2 3, 1–3 1, 2–3 7, 2–4 5, 3–4 2, 3–5 8, 4–5 6. Run Prim from vertex 1 and give the order in which edges are added.
A square A–B–C–D–A has every edge of weight 1. How many MSTs does it have? What if the weights are 1, 2, 3, 4 around the square?
Run Prim's algorithm on the example graph (A–C 1, C–D 2, A–D 3, B–C 4, A–B 5, D–E 6, B–E 7, E–F 8, D–F 9) starting from F. In what order are the edges added?
Using Cayley's formula and related results, find the number of spanning trees of (a) K₆, (b) the cycle C₇, (c) K₂,₃.
Find the MST weight of the graph A–B 3, A–C 6, B–C 2, B–D 5, C–D 4, C–E 7, D–E 1, and list the edges Kruskal rejects or never examines.
True or false? (a) Every MST contains the lightest edge of the graph. (b) The MST contains the shortest path between every pair of vertices. (c) If the strictly heaviest edge of the graph lies on a cycle, it is not in the MST. (d) Kruskal's algorithm can be applied to a disconnected graph.
The example graph's MST has weight 21. What is the MST weight if (a) every edge weight is doubled, (b) every edge weight is increased by 3? Do the MST edges change?
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.