Chapter 23: Minimum Spanning Trees

September 03, 2022

Thomas 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 TET \subseteq E that connects all of the vertices and whose total weight is minimized.

Introduction to Algorithms Second Edition, page 561

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 O(ElgV)O(ElgV) time if it uses an optimal disjoint-set-forest implementation.

MST-KRUSKAL(GG, ww)
  1. AA \larr \emptyset
  2. create V|V| trees, one containing each vertex
  3. sort the edges of EE into nondecreasing order by weight ww
  4. for each edge (u,v)(u,v) ϵ\epsilon EE, taken in nondecreasing order by weight
  5. \qquaddo if uu and vv are not in the same set
  6. \qquad\qquadthen AA{(u,v)}A \larr A \cup \{(u,v)\}
  7. \qquad\qquad\qquadjoin the sets that contain uu and vv
  8. return AA
Introduction to Algorithms Second Edition, noncontiguously from pages 569-570

Prim's Algorithm:

Prim's starts at the root, rr, 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 O(E+VlgV)O(E+VlgV) with a Fibonacci heap or slower, in O(ElgV)O(ElgV), with a binary min-heap.

MST-PRIM(GG, ww, rr)
  1. [ initialize key[u]=key[u]=\infty and π[u]=nil\pi[u]=nil for every uu ϵ\epsilon V[G]V[G] ]
  2. key[r]0key[r] \larr 0
  3. QV[G]Q \larr V[G]
  4. while QQ \neq \emptyset
  5. \qquaddo uEXTRACT-MIN(Q)u \larr \text{EXTRACT-MIN}(Q)
  6. \qquad\qquadfor each vv ϵ\epsilon Adj[u]Adj[u]
  7. \qquad\qquad\qquaddo if vv ϵ\epsilon QQ and w(u,v)<key[v]w(u,v) \lt key[v]
  8. \qquad\qquad\qquad\qquadthen π[v]u\pi[v] \larr u
  9. key[v]w(u,v)\qquad\qquad\qquad\qquad\qquad key[v] \larr w(u,v)
  10. [ π\pi is a parent function that contains the MST ]
Introduction to Algorithms Second Edition, noncontiguously from page 572