DEV Community

Academic Quant
Academic Quant

Posted on Originally published at academicquant.co.uk

Minimum spanning tree: 55 trees to compare, or 5 edges to look at

I'll use a small example throughout this article. Suppose you're responsible for six locations (labelled A to F) and nine possible connections you could build between them, each with its own construction cost, and you'd like every location connected for the smallest possible total. That's precisely the minimum spanning tree problem.

These are the connections I'll use, together with their costs:

Link A-B A-C B-C B-D C-D D-E D-F E-F B-E
Cost 4 2 5 3 6 2 7 1 8

A spanning tree on six nodes always has exactly five edges, so the direct approach is to try every set of five links and keep the ones that connect everything without a loop before taking the cheapest. There are 126 sets of five and 55 of them are spanning trees (the cheapest costs 12). I counted these by brute force, which is perfectly reasonable at this size. However, the number of spanning trees grows explosively as the graph gets bigger, so I wouldn't recommend it beyond a handful of nodes.

I prefer Kruskal's algorithm here because it never compares whole trees at all. You sort the links by cost and work down the list, keeping each link unless its two ends are already joined, and on this graph you'd keep E-F (1), A-C (2), D-E (2), B-D (3) and A-B (4). At that point you've already collected five connections and you can stop, with a total of 12 (identical to the brute force answer) after examining only five candidates.

Why taking the cheapest link is safe

Imagine dividing the locations into any two separate groups. Of the links that cross between them, the cheapest one belongs to some minimum spanning tree, because if a tree left it out you could add it (making a loop that crosses the split twice) and then drop the other crossing link on that loop to get a tree that costs no more. Each link Kruskal keeps is the cheapest one across the split between the group it joins and everything else, which is why I'd consider every individual choice it makes perfectly safe.

The "already joined" check is usually done with union-find, and with path compression and union by size each check is very close to constant time, so the sort dominates and the whole algorithm is O(m log m) for m links.

def kruskal(nodes, edges):
    parent = {n: n for n in nodes}

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    kept = []
    for u, v, w in sorted(edges, key=lambda e: e[2]):
        a, b = find(u), find(v)
        if a != b:
            parent[a] = b
            kept.append((u, v, w))
    return kept
Enter fullscreen mode Exit fullscreen mode

When the graph is disconnected

If you take out B-D, C-D and B-E, the sites fall into two separate pieces (A, B and C on one side, D, E and F on the other), and there's no longer any spanning tree because nothing joins them. However, you can still ask for a minimum spanning forest, which is simply a minimum spanning tree inside each piece.

The code above already gives you that, since it doesn't stop at five links. It keeps E-F, A-C, D-E and A-B, rejects B-C and D-F because their ends are already joined, and finishes with four links costing 9. Six nodes in two pieces gives 6 - 2 = 4 links, and the count of groups left in union-find tells you how many pieces there were. Prim's algorithm grows a single tree from one start node, so for a forest you'd have to restart it in each piece.

If an interviewer mentions that the graph might not be connected, I'd suggest saying straight away which one you'll return (the forest, or a message that no tree exists).

The full lesson, with a step-by-step run of Kruskal and Prim's algorithm on the same graph, is here: https://academicquant.co.uk/coding-graphs-minimum-spanning-tree?utm_source=devto&utm_medium=post&utm_campaign=devto-mst-kruskal-why

Top comments (0)