Chapter 23: Minimum Spanning Trees
September 03, 2022Thomas H. Cormen, Charles E. Leiserson, Ronald Rivest, Clifford Stein. Introduction to Algorithms, Second Edition. The MIT Press, 2001
Solving the minimum-spanning-tree problem.
A minimum-weight spanning tree (MST) is
an acyclic subset that connects all of the vertices and whose total weight is minimized.
23.2 The Algorithms of Kruskal and Prim
Kruskal's and Prim's are greedy algorithms. At each step, they add the lightest safe edge to the MST. A safe edge connects two previously unconnected subtrees of the final MST.
Kruskal's Algorithm:
For each edge in nondecreasing order by weight, Kruskal's adds that edge to the MST if it joins two current subtrees of the MST. Kruskal's runs in time if it uses an optimal disjoint-set-forest implementation.
MST-KRUSKAL(, )
- create trees, one containing each vertex
- sort the edges of into nondecreasing order by weight
- for each edge , taken in nondecreasing order by weight
- do if and are not in the same set
- then
- join the sets that contain and
- return
Prim's Algorithm:
Prim's starts at the root, , and adds the lightest edge connected to the current MST. As each edge is considered, any neighbors that aren't already in the MST are relaxed. Prim's runs in with a Fibonacci heap or slower, in , with a binary min-heap.
MST-PRIM(, , )
- [ initialize and for every ]
- while
- do
- for each
- do if and
- then
- [ is a parent function that contains the MST ]