Skip to main content

lib_jsl_graph/
spanning_trees.rs

1//! Minimum spanning trees (forests) of undirected graphs: Kruskal and Prim.
2//!
3//! See the book entry [Minimum spanning trees and union-find](https://jwkunz.github.io/lib_jsl/book/graph/spanning-trees.html).
4
5use crate::graph::{Edge, Graph, UnionFind};
6use lib_jsl_core::ErrorsJSL;
7use std::cmp::Ordering;
8use std::collections::BinaryHeap;
9
10/// A minimum spanning forest: its edges and total weight (one tree per connected component).
11#[derive(Debug, Clone, PartialEq)]
12pub struct SpanningForest {
13    pub edges: Vec<Edge>,
14    pub weight: f64,
15}
16
17fn undirected(g: &Graph) -> Result<(), ErrorsJSL> {
18    if g.is_directed() {
19        return Err(ErrorsJSL::InvalidInputRange("Spanning trees need an undirected graph."));
20    }
21    Ok(())
22}
23
24/// Kruskal's algorithm: edges by increasing weight, kept when they join two components
25/// (union-find). `O(E log E)`.
26pub fn kruskal(g: &Graph) -> Result<SpanningForest, ErrorsJSL> {
27    undirected(g)?;
28    // ANCHOR: kruskal
29    let mut edges = g.edges();
30    edges.sort_by(|a, b| a.weight.total_cmp(&b.weight));
31    let mut sets = UnionFind::new(g.vertex_count());
32    let chosen: Vec<Edge> = edges.into_iter().filter(|e| sets.union(e.from, e.to)).collect();
33    // ANCHOR_END: kruskal
34    let weight = chosen.iter().map(|e| e.weight).sum();
35    Ok(SpanningForest { edges: chosen, weight })
36}
37
38#[derive(PartialEq)]
39struct Candidate(f64, usize, usize);
40impl Eq for Candidate {}
41impl PartialOrd for Candidate {
42    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
43        Some(self.cmp(other))
44    }
45}
46impl Ord for Candidate {
47    fn cmp(&self, other: &Self) -> Ordering {
48        other.0.total_cmp(&self.0)
49    }
50}
51
52/// Prim's algorithm: grows each tree from a root by the cheapest edge leaving it (binary heap).
53/// `O(E log V)`; better than Kruskal on dense graphs.
54pub fn prim(g: &Graph) -> Result<SpanningForest, ErrorsJSL> {
55    undirected(g)?;
56    let n = g.vertex_count();
57    let mut in_tree = vec![false; n];
58    let mut chosen = Vec::new();
59    for root in 0..n {
60        if in_tree[root] {
61            continue;
62        }
63        in_tree[root] = true;
64        let mut heap: BinaryHeap<Candidate> = g.neighbors(root).iter().map(|&(v, w)| Candidate(w, root, v)).collect();
65        while let Some(Candidate(w, u, v)) = heap.pop() {
66            if in_tree[v] {
67                continue;
68            }
69            in_tree[v] = true;
70            chosen.push(Edge { from: u, to: v, weight: w });
71            heap.extend(g.neighbors(v).iter().filter(|&&(x, _)| !in_tree[x]).map(|&(x, wx)| Candidate(wx, v, x)));
72        }
73    }
74    let weight = chosen.iter().map(|e| e.weight).sum();
75    Ok(SpanningForest { edges: chosen, weight })
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn both_algorithms_find_the_same_minimum_weight() {
84        // The classic 9-vertex example: MST weight 37.
85        let g = Graph::from_edges(
86            9,
87            &[(0, 1, 4.0), (0, 7, 8.0), (1, 2, 8.0), (1, 7, 11.0), (2, 3, 7.0), (2, 8, 2.0), (2, 5, 4.0), (3, 4, 9.0), (3, 5, 14.0), (4, 5, 10.0), (5, 6, 2.0), (6, 7, 1.0), (6, 8, 6.0), (7, 8, 7.0)],
88            false,
89        )
90        .unwrap();
91        let (k, p) = (kruskal(&g).unwrap(), prim(&g).unwrap());
92        assert_eq!((k.weight, p.weight), (37.0, 37.0));
93        assert_eq!((k.edges.len(), p.edges.len()), (8, 8));
94        // A forest for a disconnected graph, and directed graphs are rejected.
95        let forest = Graph::from_edges(5, &[(0, 1, 1.0), (1, 2, 2.0), (0, 2, 5.0), (3, 4, 3.0)], false).unwrap();
96        assert_eq!((kruskal(&forest).unwrap().weight, prim(&forest).unwrap().weight), (6.0, 6.0));
97        assert!(kruskal(&Graph::new(2, true)).is_err() && prim(&Graph::new(2, true)).is_err());
98    }
99}