Minimum Spanning Tree: Kruskal and Prim
You need to connect seven towns with power lines. Each place where you could lay a line has its own cost. Which lines should you pick so that every town is connected for the least money? Step through two ways to do it.
Short answer. A minimum spanning tree is the set of lines that connects every dot with no loops, at the lowest total cost. It always has (number of dots − 1) lines. Kruskal looks at the lines from the cheapest up and skips only the ones that would close a loop. Prim starts at one dot and keeps adding the cheapest line that leaves its group. Both reach the same total. This is a different problem from the shortest path out of one dot (Dijkstra).
Pick a method above and press "Next". Thick green lines are taken. Faint dashed lines with a stroke through the cost are skipped. The orange band and orange outline mark the line looked at in this step. Orange arrows show what this step does: in the row of lines, the line being looked at; on the graph, the side a taken line joins (the group that merges in, the dot that comes in). Orange dots are the path that would close a loop. In Kruskal, the small number next to each dot is its group, and the same number means the same group. In Prim, the pale green area is the group, its outline is the border, and blue dashed lines cross the border (the candidates). The graph and the costs are made up.
Definitions
The text below explains in plain words. These are the textbook definitions, which say vertex for a dot and edge for a line. G = (V, E) is an undirected, connected, weighted graph, and w(e) is the weight of edge e. When we write running time, V and E stand for the number of vertices and edges.
- spanning tree
- A subgraph of G that contains every vertex, is connected, and has no cycle. If there are V vertices, a spanning tree has exactly V − 1 edges.
- minimum spanning tree (MST)
- Among the spanning trees of G, a spanning tree T whose total edge weight W(T) is the smallest. If all the weights are different, there is only one minimum spanning tree.
- cut, cut property
- A cut splits the vertex set V into two sets S and V − S, neither of them empty. A crossing edge has one end in S and the other end in V − S. Cut property: when all the weights are different, for any cut, the crossing edge with the smallest weight is in the minimum spanning tree.
- Kruskal's algorithm
- A minimum spanning tree algorithm that looks at the edges from the smallest weight up and adds an edge only if its two ends are in different connected components (so it makes no cycle with the edges already picked), until it has V − 1 edges. The worst case takes O(E log E) time.
- Prim's algorithm
- A minimum spanning tree algorithm that starts from a tree of one vertex and repeats this until every vertex is in: among the edges that join a vertex in the tree to a vertex outside it, add the one with the smallest weight, together with that outside vertex. The worst case takes O(E log E) (lazy), O(E log V) (eager), or O(V²) (array) time, depending on how it is built.
- union-find
- A data structure that holds disjoint sets and gives two operations: find, which returns the representative (root) of the set an element is in, and union, which joins two sets into one. Kruskal's algorithm checks whether the two ends u and v of an edge are already in the same connected component by testing whether their roots are the same (find(u) = find(v)).
1. The problem: connect every dot as cheaply as possible
You have some dots and some lines, each line joining two dots. Every line has a cost. Think of towns, the places where you could lay a power line between them, and the cost of each one. The job is to pick lines so that every dot is connected, while the total cost is as small as possible.
The set of lines you end up with follows two rules.
- No loops. If there were a loop, you could remove one of its lines and everything would still be connected. When all costs are positive, removing it is cheaper.
- Exactly (number of dots − 1) lines. Connecting V dots with no loops always takes exactly V − 1 lines. The lab has 7 dots, so 6 lines.
A set of lines that connects every dot with no loops is called a spanning tree. The one with the smallest total is the minimum spanning tree. There is only one number to measure.
W(T) = w(e₁) + w(e₂) + … + w(e_{V−1})
T: the lines you picked (a spanning tree).e₁, e₂, …: the lines in T. There are V − 1 of them.w(e): the cost of line e.V: the number of dots.W(T): the total of T. We look for the T that makes this smallest.
The lab graph has 7 dots and 12 lines, and its minimum spanning tree has a total of 24.
2. Kruskal: cheapest lines first, skip loops
- Line up the lines from the cheapest to the most expensive.
- Look at them one by one. If the two ends are still in different groups, take the line. The two groups become one.
- If the two ends are already connected, skip the line. Taking it would close a loop.
- Stop once you have V − 1 lines.
At the start every dot is its own group, so there are 7 groups. Each line you take merges two groups, until one is left. Section 5 shows a fast way to ask "are the two ends already connected?".
Try this. With Kruskal, "Next" takes two steps per line: first it compares the group numbers of the two ends, then it takes or skips the line. It takes E–F 1, D–G 2, B–F 3, A–B 4 and C–F 5 in turn. The sixth line looked at, B–C 6, is skipped because B and C are already connected through F. A–F 7 and A–E 8 are skipped too. Taking C–D 9 makes 6 lines, so it ends at step 19. The total is 1 + 2 + 3 + 4 + 5 + 9 = 24. F–G 10, C–G 11 and E–G 12 are never even looked at.
3. Prim: grow one group a dot at a time
- Start a group with any one dot. The lab starts at A.
- Among the lines that join a dot inside the group to a dot outside, take the cheapest. The outside dot joins the group.
- A line whose two ends are both inside the group can never be used, so drop it.
- Stop when every dot is in the group (V − 1 lines).
Try this. Switch to Prim and it takes two steps per dot (compare the lines that cross the border, then take the cheapest). It takes A–B 4, B–F 3, E–F 1, C–F 5, C–D 9 and D–G 2 in turn, ending at step 13 with a total of 24. The six lines are the same as Kruskal's, only the order differs. Kruskal takes E–F (cost 1) first, while Prim takes it third. Until the group reaches F, E–F is not a line that leaves the group.
The self-check on this page (add ?test to the address) confirms that the two methods agree. It checks that both totals are 24 and the lines are the same, that Prim gives 24 from any of the seven starting dots, and that trying all 924 ways to pick 6 of the 12 lines finds no spanning tree cheaper than 24.
4. Follow it by hand
This is the same graph as the lab. Kruskal looks at the lines in order of cost.
| Order | Line | Cost | Ends already connected? | Action | Total |
|---|---|---|---|---|---|
| 1 | E–F | 1 | no | take | 1 |
| 2 | D–G | 2 | no | take | 3 |
| 3 | B–F | 3 | no | take | 6 |
| 4 | A–B | 4 | no | take | 10 |
| 5 | C–F | 5 | no | take | 15 |
| 6 | B–C | 6 | yes (B–F–C) | skip | 15 |
| 7 | A–F | 7 | yes (A–B–F) | skip | 15 |
| 8 | A–E | 8 | yes (A–B–F–E) | skip | 15 |
| 9 | C–D | 9 | no | take. 6 lines, done | 24 |
Prim starts at A and only looks at the lines that leave the group.
| Order | Group | Lines that leave it (cost) | Taken (the cheapest of them) | Total |
|---|---|---|---|---|
| 1 | A | A–B 4, A–F 7, A–E 8 | A–B | 4 |
| 2 | A, B | B–F 3, B–C 6, A–F 7, A–E 8 | B–F | 7 |
| 3 | A, B, F | E–F 1, C–F 5, B–C 6, A–E 8, F–G 10 | E–F | 8 |
| 4 | A, B, F, E | C–F 5, B–C 6, F–G 10, E–G 12 | C–F | 13 |
| 5 | A, B, F, E, C | C–D 9, F–G 10, C–G 11, E–G 12 | C–D | 22 |
| 6 | A, B, F, E, C, D | D–G 2, F–G 10, C–G 11, E–G 12 | D–G | 24 |
5. Asking "already connected?" fast: union-find
For every line, Kruskal asks "are the two ends already connected?". If you answered by searching along the lines taken so far, you would walk the graph again for every question. Union-find is a small data structure that answers this question fast.
- One cell per dot. Each dot has a cell that names the dot it points to. At the start every dot points to itself.
- Same group? (find). Follow the cells until you reach a dot that points to itself. That dot is the group's leader. Two dots are in the same group when they have the same leader.
- Connect (union). Find the leaders of both dots and make one leader point to the other. Always put the tree with fewer dots under the tree with more. Then no dot is more than lg n steps from its leader. Here n is the number of dots, and lg n is how many times you multiply 2 to reach n.
Pick two dots and press "Connect" or "Same group?". Each arrow shows the dot that a cell points to. The path you just climbed to the leader, and its cells, turn orange. The picture is the table below drawn as trees.
Try this. Connect E–F, D–G, B–F, A–B and C–F, in the order Kruskal took them. Then press "Same group?" with B and C: B → E and C → E, so both leaders are E. That is why Kruskal skipped B–C. Next, connect C and D. The tree of leader D (2 dots) goes under the tree of leader E (5 dots). Now pick G and you climb two steps: G → D → E. Even with all 7 dots connected, the farthest dot is two steps from the leader (lg 7 is about 2.8).
Path compression. If every dot you pass on the way up is changed to point straight at the leader, the next question is shorter. With both tricks (smaller tree under the bigger one, and path compression), the work per question is nearly constant on average. The source says this is bounded by a function (the inverse Ackermann function) that is less than 5 for any n that comes up in practice. The lab above skips path compression so that the climb stays easy to see.
Here is Kruskal in a few lines of Python. To keep it short, it leaves out the tree size check and path compression.
def kruskal(n, edges): # edges: [(cost, u, v), ...], dots are 0 to n-1
parent = list(range(n)) # at first every dot is its own leader
def find(x): # follow the cells up to the leader
while parent[x] != x:
x = parent[x]
return x
tree = []
for w, u, v in sorted(edges): # cheapest line first
ru, rv = find(u), find(v)
if ru != rv: # take it only if the groups differ
parent[rv] = ru # connect
tree.append((w, u, v))
return tree
Prim puts the candidate lines in a heap and pulls out the cheapest. In Python that is one line: w, u, v = heapq.heappop(candidates).
6. Why "cheapest line first" works: the cut property
Split the dots into two groups any way you like. A line that joins a dot in one group to a dot in the other is a crossing line. The source states this property: the cheapest crossing line is always in the minimum spanning tree (when all costs are different). The two groups have to be joined by some line in the end, and that line is the cheapest crossing one.
- Prim uses the property directly. It splits the dots into "the group" and "the rest" and takes the cheapest line across that border.
- When Kruskal takes a line u–v, split the dots into u's group and the rest. Every line cheaper than u–v has already been looked at, and whether it was taken or skipped, both of its ends sit inside one group, so it does not cross this border. That makes u–v the cheapest crossing line.
Taking whatever looks best right now and never going back is called a greedy algorithm. The source explains both methods as special cases of a greedy algorithm. Greedy choices do not always give the right answer, but for this problem the cut property promises that they do.
7. Properties to know
| Property | In plain words | In the lab |
|---|---|---|
| V − 1 lines, no loops | Connecting V dots with no loops always takes exactly V − 1 lines | 7 dots, 6 lines taken |
| All costs different: only one tree | There is only one minimum spanning tree, so every method returns the same lines | Kruskal and Prim take the same 6 lines |
| Costs may be zero or negative | Costs do not have to be distances. Kruskal and Prim still work | Self-check: subtract 5 from every cost and you get the same lines, total −6 |
| Not the shortest path | The path between two dots along the tree may not be the shortest path | D to F: 14 along the tree, 12 on the shortest path |
| The graph must be connected | A graph in pieces has no spanning tree. You solve each piece on its own | FAQ 3 |
8. Which one to use
The running times are the source's worst case. The source does not list best or typical cases separately.
| Method | Time (worst case) | Extra memory | Good | Bad | Use when |
|---|---|---|---|---|---|
| Kruskal | E log E. Twice the lines, a bit more than twice the time | grows with the number of lines E | Needs only a list of lines. Short to write with a sort and union-find | Has to handle every line in order of cost | There are few lines, or the data comes as a list of lines |
| Prim (lazy) | E log E | grows with E | Grows the group with one priority queue | Keeps lines that are now inside the group in the queue and throws them out only when it pulls them | You want a Prim that is easy to write |
| Prim (eager) | E log V | grows with the number of dots V | Keeps only one line per outside dot in the queue: its cheapest line to the group | Needs a priority queue that can lower a value | There are few or a medium number of lines |
| Prim (array) | V². Twice the dots, four times the time | grows with V | No queue: it scans an array to find the closest dot | Costs V² even when there are few lines | There are very many lines. The source calls it the best fit for dense graphs |
V: the number of dots.E: the number of lines.log: how many times you multiply 2 to reach the number. Doubling the number adds only 1.E log E: the work to handle E lines in order of cost. It is the same size as sorting the lines (time complexity).
With few lines (E close to V), Kruskal's E log E and eager Prim's E log V are about the same. Pick whichever is easier to write. With many lines (almost every dot joined to almost every other, so E is close to V²), E log E grows to about V² × log, which is more than the array Prim's V².
Where it is used
- Laying wires and pipes. When you connect many points with wires, pipes or roads, it finds the layout with the lowest total building cost.
- Building networks. When you link many sites with cables, it picks the connections with the lowest total cable cost.
Frequently asked
How is this different from Dijkstra's shortest path?
Dijkstra finds the shortest path from one dot to the others. A minimum spanning tree makes the total cost of the lines that connect every dot as small as possible. So a path along the tree is not promised to be the shortest path. In the lab graph, the path from D to F along the tree is D–C–F, 9 + 5 = 14, but the shortest path is D–G–F, 2 + 10 = 12.
What if two lines have the same cost?
Both methods still work. But there can be more than one minimum spanning tree, so the lines you get can depend on which of the equal lines you look at first. Either way, the total is the same smallest number.
What if the graph is in two pieces?
Then no tree connects every dot. You find a minimum spanning tree for each piece, and together they are called a minimum spanning forest. Kruskal gives the tree of every piece at once if it looks at all the lines. Prim has to start again in each piece.
Words
| Word used here | Textbook term |
|---|---|
| dot | vertex, node |
| line | edge |
| cost of a line | weight. A graph with costs is an edge-weighted graph |
| loop | cycle |
| lines that connect every dot with no loops | spanning tree |
| spanning tree with the smallest total | minimum spanning tree (MST) |
| group | connected component |
| splitting into two groups, crossing line | cut, crossing edge |
| the cheapest crossing line is in the tree | cut property |
| taking what looks best right now | greedy algorithm |
| the structure that answers "already connected?" | union-find |
| leader | root |
| putting the smaller tree under the bigger one | weighted quick-union |
| pointing straight at the leader | path compression |
| a queue that hands out the cheapest item | priority queue |
| one tree for each piece of a graph in pieces | minimum spanning forest |
Sources
- Robert Sedgewick, Kevin Wayne, Algorithms, 4.3 Minimum Spanning Trees. The definition and assumptions (connected graph, costs may be zero or negative, equal costs may give more than one tree, minimum spanning forest), the cut property and the greedy algorithm, the steps of Kruskal and Prim (lazy and eager), their time and memory, and V² for the array version of Prim.
- Robert Sedgewick, Kevin Wayne, Algorithms, 1.5 Case Study: Union-Find. Climbing to the leader (quick-union), putting the smaller tree under the bigger one with depth at most lg n, and path compression with the inverse Ackermann function.