Minimum spanning tree
A minimum spanning tree joins all vertices with the least total edge weight. Kruskal sorts edges and adds each one that does not create a cycle (checked with disjoint sets); Prim grows one tree from a vertex, always adding the cheapest edge leaving it. With distinct weights the tree is unique. Kirchhoff's theorem counts all spanning trees with a determinant.
How to recognise it
- Connect everything as cheaply as possible.
- Choosing edges so that no cycle forms.
- Counting the spanning trees of a graph.
Two greedy methods
kruskal: sort edges by weight; for (u, v, w): if find(u) != find(v): take it; union(u, v)
prim: tree = {0}; heap = edges from 0
while heap: take the cheapest edge (u, v); if v not in tree: add v and its edges
Vertices, edges, adjacency lists and the other words used here are on the Structures page.
Both rely on the cut property: the cheapest edge crossing any split of the vertices belongs to some minimum spanning tree.
Counting spanning trees
Build the Laplacian (degrees on the diagonal, -1 for every edge), delete one row and the matching column, and take the determinant.
Common mistakes
- Forgetting that Prim's heap can hold edges to vertices already in the tree.
- Assuming the graph is connected.
Problems
- Find the MST weightmediumguide ready
- Implement Kruskal’s Algorithmmediumguide ready
- Implement Prim’s Algorithmmediumguide ready
- Total no. of Spanning tree in a graphmediumguide ready