TExcelTAD
Home › Data Structures & Algorithms › Minimum Spanning Tree Intro

Minimum Spanning Tree Intro

Imagine you must connect six villages with fibre-optic cable. You know what each possible connection would cost. Which connections should you build so that every village is connected (directly or through others) and the total cost is as small as possible?

That is the minimum spanning tree (MST) problem. Given a connected, undirected, weighted graph:

  • A spanning tree is a subset of the edges that connects all V vertices and contains no cycle. It always has exactly V - 1 edges.
  • A minimum spanning tree is a spanning tree whose total weight is as small as possible.

A cycle is never needed: if the chosen edges contained one, you could remove any edge of the cycle and everything would stay connected, at a lower cost.

The example graph

This graph is used in this lesson and the next two:

Vertex Edges (neighbour: weight)
A B: 7, C: 3
B A: 7, C: 2, D: 5
C A: 3, B: 2, D: 6, E: 4
D B: 5, C: 6, E: 8, F: 1
E C: 4, D: 8, F: 9
F D: 1, E: 9

Edges and weights: A-B 7, A-C 3, B-C 2, B-D 5, C-D 6, C-E 4, D-E 8, D-F 1, E-F 9.

Checking a spanning tree

python · try it yourself
edges = {("A", "B"): 7, ("A", "C"): 3, ("B", "C"): 2, ("B", "D"): 5, ("C", "D"): 6,
         ("C", "E"): 4, ("D", "E"): 8, ("D", "F"): 1, ("E", "F"): 9}
vertices = "ABCDEF"

def is_spanning_tree(chosen):
    if len(chosen) != len(vertices) - 1:
        return False
    group = {v: v for v in vertices}                 # tiny union-find
    def find(x):
        while group[x] != x:
            x = group[x]
        return x
    for a, b in chosen:
        ra, rb = find(a), find(b)
        if ra == rb:
            return False                             # this edge closes a cycle
        group[ra] = rb
    return True

def weight(chosen):
    return sum(edges[e] for e in chosen)

guess = [("A", "B"), ("A", "C"), ("C", "D"), ("D", "F"), ("E", "F")]
best = [("D", "F"), ("B", "C"), ("A", "C"), ("C", "E"), ("B", "D")]
for name, chosen in [("guess", guess), ("best", best)]:
    print(name, is_spanning_tree(chosen), weight(chosen))
guess True 26
best True 15

Both choices connect everything, but the second one costs 15 instead of 26.

Brute force: try every spanning tree

For a tiny graph we can try every subset of V - 1 edges and keep the cheapest valid one. This proves 15 is optimal here, but the number of subsets explodes quickly, so real algorithms must be smarter.

python · try it yourself
from itertools import combinations

edges = {("A", "B"): 7, ("A", "C"): 3, ("B", "C"): 2, ("B", "D"): 5, ("C", "D"): 6,
         ("C", "E"): 4, ("D", "E"): 8, ("D", "F"): 1, ("E", "F"): 9}
vertices = "ABCDEF"

def connects_all(chosen):
    reached, frontier = {"A"}, ["A"]
    while frontier:
        u = frontier.pop()
        for a, b in chosen:
            for x, y in ((a, b), (b, a)):
                if x == u and y not in reached:
                    reached.add(y)
                    frontier.append(y)
    return len(reached) == len(vertices)

trees = [c for c in combinations(edges, len(vertices) - 1) if connects_all(c)]
best = min(trees, key=lambda c: sum(edges[e] for e in c))
print("spanning trees:", len(trees), "of", len(list(combinations(edges, 5))), "subsets")
print("cheapest:", sorted(best), sum(edges[e] for e in best))
spanning trees: 55 of 126 subsets
cheapest: [('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E'), ('D', 'F')] 15

The cut property: why greedy works

Split the vertices into two groups in any way (a cut). Of all edges that cross from one group to the other, the cheapest one belongs to an MST. Intuition: some edge must cross the cut to connect the groups, and swapping any more expensive crossing edge for the cheapest one can only lower the total.

Both classic MST algorithms are greedy: they repeatedly add the cheapest edge that is safe according to the cut property.

Algorithm Grows Picks next Needs Time
Prim's one tree from a start vertex cheapest edge leaving the tree a priority queue O(E log V)
Kruskal's a forest that merges into one tree cheapest edge overall that doesn't close a cycle sorting + union-find O(E log E)

Uses of minimum spanning trees

  • Designing networks: cables, pipes, roads, electrical grids.
  • Clustering: build the MST, then delete the k - 1 most expensive edges to get k groups of similar items.
  • Approximating hard problems: an MST gives a tour at most twice the optimum for the metric Traveling Salesman problem.
  • Image segmentation and analysing networks of similar documents or genes.

Note: If all edge weights are different, the MST is unique. With equal weights there can be several MSTs, all with the same total weight.

Test yourself

How many edges does a spanning tree of a graph with 10 vertices have?

  1. 9
  2. 10
  3. 11
  4. 45

Why can a minimum spanning tree never contain a cycle?

  1. Cycles are not allowed in graphs
  2. Removing one cycle edge keeps everything connected and lowers the cost
  3. Cycles make the graph directed
  4. It can, if the weights are small

What does the cut property say?

  1. The most expensive edge is in every MST
  2. The cheapest edge crossing any cut belongs to an MST
  3. Every cut has exactly one edge
  4. MSTs are unique