Courses / DSA Patterns for Working Engineers / Chapter 37
Module 11 · Graph algorithms · Chapter 37 of 39
Minimum Spanning Trees: Kruskal and Prim
Builds on Union-Find: Merging Groups and Finding Redundant Links and Heaps and Two Heaps: Running Medians and Priority Scheduling. Next up: Advanced Graph Algorithms: Bridges, Strong Components and Euler Paths.
Part 1 · Introduction to minimum spanning trees
Spanning trees and the cheapest one
A phone company must connect every village in a district with cable, and every kilometre of cable costs money. The cheapest way to connect everyone is a minimum spanning tree.
Take a connected undirected graph whose edges have weights. A spanning tree is a set of edges that connects all n nodes and contains no cycle. Every spanning tree has exactly n - 1 edges: fewer cannot connect n nodes, and one more must close a cycle. A minimum spanning tree, or MST, is a spanning tree with the smallest possible total weight.
Two facts about trees are used throughout. Adding any edge to a spanning tree creates exactly one cycle. And removing any edge from a cycle leaves everything connected, because the rest of the cycle still links its ends. With positive weights, a connected set of edges that contains a cycle can always be made cheaper by dropping one edge of the cycle, so a cheapest connected set is a tree.
This chapter has two algorithms. Kruskal's sorts all edges and adds them lightest first, skipping any that would close a cycle. Prim's grows one tree from a start node, always adding the lightest edge that leaves the tree. They look different, and one idea proves both.