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.

W(T)=∑e∈Tw(e)

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.

{{u,v}∈E∣u∈S, v∉S}

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.

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})

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

  1. Line up the lines from the cheapest to the most expensive.
  2. Look at them one by one. If the two ends are still in different groups, take the line. The two groups become one.
  3. If the two ends are already connected, skip the line. Taking it would close a loop.
  4. 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?".

1. B–F 3: different groups 6513 BCFE 2355 take: group 2 → group 5 2. B–C 6: same group 6513 BCFE 5555 loop B–F–C–B, so skip
What Kruskal does with one line. The small number next to each dot is its group (as in the lab). 1. If the ends have different numbers, take the line, and the two groups become one. 2. If the numbers match, a path between the ends (orange dots) already exists, so taking the line would close a loop. Skip it. A, D, G and their lines are left out.

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

  1. Start a group with any one dot. The lab starts at A.
  2. Among the lines that join a dot inside the group to a dot outside, take the cheapest. The outside dot joins the group.
  3. A line whose two ends are both inside the group can never be used, so drop it.
  4. Stop when every dot is in the group (V − 1 lines).
1. Compare lines across the border 43678 cheapest ABCFE the cheapest is B–F 3 2. Take B–F 3, F comes in 4367815 ABCFE A–F 7: both ends inside, drop
One dot of Prim. The pale green area is the group and its outline is the border. 1. Compare the costs of the lines that cross the border (blue dashes). 2. Take the cheapest one: F comes inside and the border grows. Now E–F 1 and C–F 5 cross the border too. D, G and their lines are left out.

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.

OrderLineCostEnds already connected?ActionTotal
1E–F1notake1
2D–G2notake3
3B–F3notake6
4A–B4notake10
5C–F5notake15
6B–C6yes (B–F–C)skip15
7A–F7yes (A–B–F)skip15
8A–E8yes (A–B–F–E)skip15
9C–D9notake. 6 lines, done24

Prim starts at A and only looks at the lines that leave the group.

OrderGroupLines that leave it (cost)Taken (the cheapest of them)Total
1AA–B 4, A–F 7, A–E 8A–B4
2A, BB–F 3, B–C 6, A–F 7, A–E 8B–F7
3A, B, FE–F 1, C–F 5, B–C 6, A–E 8, F–G 10E–F8
4A, B, F, EC–F 5, B–C 6, F–G 10, E–G 12C–F13
5A, B, F, E, CC–D 9, F–G 10, C–G 11, E–G 12C–D22
6A, B, F, E, C, DD–G 2, F–G 10, C–G 11, E–G 12D–G24

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.

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.

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

PropertyIn plain wordsIn the lab
V − 1 lines, no loopsConnecting V dots with no loops always takes exactly V − 1 lines7 dots, 6 lines taken
All costs different: only one treeThere is only one minimum spanning tree, so every method returns the same linesKruskal and Prim take the same 6 lines
Costs may be zero or negativeCosts do not have to be distances. Kruskal and Prim still workSelf-check: subtract 5 from every cost and you get the same lines, total −6
Not the shortest pathThe path between two dots along the tree may not be the shortest pathD to F: 14 along the tree, 12 on the shortest path
The graph must be connectedA graph in pieces has no spanning tree. You solve each piece on its ownFAQ 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.

MethodTime (worst case)Extra memoryGoodBadUse when
KruskalE log E. Twice the lines, a bit more than twice the timegrows with the number of lines ENeeds only a list of lines. Short to write with a sort and union-findHas to handle every line in order of costThere are few lines, or the data comes as a list of lines
Prim (lazy)E log Egrows with EGrows the group with one priority queueKeeps lines that are now inside the group in the queue and throws them out only when it pulls themYou want a Prim that is easy to write
Prim (eager)E log Vgrows with the number of dots VKeeps only one line per outside dot in the queue: its cheapest line to the groupNeeds a priority queue that can lower a valueThere are few or a medium number of lines
Prim (array)V². Twice the dots, four times the timegrows with VNo queue: it scans an array to find the closest dotCosts V² even when there are few linesThere are very many lines. The source calls it the best fit for dense graphs

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

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 hereTextbook term
dotvertex, node
lineedge
cost of a lineweight. A graph with costs is an edge-weighted graph
loopcycle
lines that connect every dot with no loopsspanning tree
spanning tree with the smallest totalminimum spanning tree (MST)
groupconnected component
splitting into two groups, crossing linecut, crossing edge
the cheapest crossing line is in the treecut property
taking what looks best right nowgreedy algorithm
the structure that answers "already connected?"union-find
leaderroot
putting the smaller tree under the bigger oneweighted quick-union
pointing straight at the leaderpath compression
a queue that hands out the cheapest itempriority queue
one tree for each piece of a graph in piecesminimum spanning forest

Sources

← Dijkstra's algorithmGreedy algorithms →