1def kruskal(nodes, edges):2 parent = {v: v for v in nodes}3 def find(x):4 while parent[x] != x:5 x = parent[x]6 return x7 tree = []8 for w, u, v in sorted(edges):9 ru, rv = find(u), find(v)10 if ru != rv:11 parent[rv] = ru12 tree.append((u, v, w))13 return treeA4B62C759D31E8Fw 1D–Ew 2A–Dw 3C–Fw 4A–Bw 5B–Ew 6B–Cw 7B–Dw 8E–Fw 9C–Erurvlen(tree)total
Pucks: the nodes; chips: each edge's weightFlowing traces: edges in the tree; crossed chips: edges that would close a loopThe rose token: the edge being triedKruskal tries the edges from lightest to heaviest. A token carries each weight from the sorted row to its edge; find() gives the root of each end. Different roots: the edge joins the tree and starts to flow. Same root: it would close a loop, so it gets a cross. Five edges, total weight 16.

The problem

  1. Six towns, A to F, and 9 possible cables. Each edge has a weight: the cost to lay it. A spanning tree links every node with no loop, so it has V − 1 = 5 edges. We want the cheapest: the minimum spanning tree.

Kruskal step by step

Why it works, what it costs

What happens

;; step 1/10 · graph
V = 6 nodes, E = 9 edges (w, u, v):
  A–B  weight 4
  B–C  weight 6
  A–D  weight 2
  B–E  weight 5
  C–F  weight 3
  D–E  weight 1
  E–F  weight 8
  B–D  weight 7
  C–E  weight 9

spanning tree: edges that link all V nodes, no loop
  it always has V − 1 = 5 edges
minimum spanning tree (MST): smallest total weight

A spanning tree of a connected graph is a set of its edges that links every node and contains no loop; it always has V − 1 edges. A minimum spanning tree has the smallest total weight of all spanning trees (MIT 6.046 Lecture 12; Sedgewick and Wayne §4.3). The cut property (MIT 6.046 calls it the greedy-choice property): for any split of the nodes into two groups, a lightest edge crossing between them belongs to some minimum spanning tree. Each edge Kruskal takes is the lightest edge leaving its tree, so the tree it builds is minimum.