Skip to main content

lib_jsl_graph/
ordering.rs

1//! Topological sorting and strongly connected components of directed graphs.
2//!
3//! See the book entry [Graphs, traversal and orderings](https://jwkunz.github.io/lib_jsl/book/graph/traversal.html#topological-sorting).
4
5use crate::graph::Graph;
6use lib_jsl_core::ErrorsJSL;
7use std::cmp::Reverse;
8use std::collections::BinaryHeap;
9
10/// A topological order (every edge `u → v` has `u` before `v`) by Kahn's algorithm, taking the
11/// smallest ready vertex at each step, so the result is the lexicographically smallest
12/// topological order. `O((V + E) log V)`. Returns an error if the graph has a cycle.
13pub fn topological_sort(g: &Graph) -> Result<Vec<usize>, ErrorsJSL> {
14    if !g.is_directed() {
15        return Err(ErrorsJSL::InvalidInputRange("Topological sorting needs a directed graph."));
16    }
17    let n = g.vertex_count();
18    let mut indegree = vec![0usize; n];
19    for e in g.edges() {
20        indegree[e.to] += 1;
21    }
22    // A min-heap of the vertices with no remaining incoming edges.
23    let mut ready: BinaryHeap<Reverse<usize>> = (0..n).filter(|&v| indegree[v] == 0).map(Reverse).collect();
24    let mut order = Vec::with_capacity(n);
25    while let Some(Reverse(u)) = ready.pop() {
26        order.push(u);
27        for &(v, _) in g.neighbors(u) {
28            indegree[v] -= 1;
29            if indegree[v] == 0 {
30                ready.push(Reverse(v));
31            }
32        }
33    }
34    if order.len() != n {
35        return Err(ErrorsJSL::RuntimeError("The graph has a cycle, so no topological order exists."));
36    }
37    Ok(order)
38}
39
40/// Strongly connected components by Tarjan's algorithm (iterative, `O(V + E)`). Returns the
41/// component label of each vertex; labels are a reverse topological order of the condensation
42/// (component 0 has no edges to other components).
43pub fn strongly_connected_components(g: &Graph) -> Vec<usize> {
44    let n = g.vertex_count();
45    let mut index = vec![usize::MAX; n];
46    let mut low = vec![0usize; n];
47    let mut on_stack = vec![false; n];
48    let mut stack = Vec::new();
49    let mut component = vec![usize::MAX; n];
50    let (mut counter, mut components) = (0, 0);
51    for root in 0..n {
52        if index[root] != usize::MAX {
53            continue;
54        }
55        // Frames of (vertex, next neighbour position).
56        let mut frames = vec![(root, 0usize)];
57        index[root] = counter;
58        low[root] = counter;
59        counter += 1;
60        stack.push(root);
61        on_stack[root] = true;
62        // ANCHOR: tarjan
63        while let Some(&mut (v, ref mut position)) = frames.last_mut() {
64            if let Some(&(w, _)) = g.neighbors(v).get(*position) {
65                *position += 1;
66                if index[w] == usize::MAX {
67                    index[w] = counter;
68                    low[w] = counter;
69                    counter += 1;
70                    stack.push(w);
71                    on_stack[w] = true;
72                    frames.push((w, 0));
73                } else if on_stack[w] {
74                    low[v] = low[v].min(index[w]);
75                }
76                continue;
77            }
78            frames.pop();
79            if let Some(&(parent, _)) = frames.last() {
80                low[parent] = low[parent].min(low[v]);
81            }
82            if low[v] == index[v] {
83                loop {
84                    let w = stack.pop().expect("v is on the stack");
85                    on_stack[w] = false;
86                    component[w] = components;
87                    if w == v {
88                        break;
89                    }
90                }
91                components += 1;
92            }
93        }
94        // ANCHOR_END: tarjan
95    }
96    component
97}
98
99/// The condensation: the directed acyclic graph of strongly connected components.
100pub fn condensation(g: &Graph) -> (Vec<usize>, Graph) {
101    let labels = strongly_connected_components(g);
102    let count = labels.iter().max().map_or(0, |m| m + 1);
103    let mut dag = Graph::new(count, true);
104    let mut seen = std::collections::HashSet::new();
105    for e in g.edges() {
106        let (a, b) = (labels[e.from], labels[e.to]);
107        if a != b && seen.insert((a, b)) {
108            dag.add_edge(a, b, 1.0).expect("labels are in range");
109        }
110    }
111    (labels, dag)
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn ties_go_to_the_smallest_ready_vertex() {
120        // With edges 0 → 3 and 2 → 1, a first-in-first-out queue gives [0, 2, 3, 1].
121        let g = Graph::from_unweighted_edges(4, &[(0, 3), (2, 1)], true).unwrap();
122        assert_eq!(topological_sort(&g).unwrap(), vec![0, 2, 1, 3]);
123    }
124
125    #[test]
126    fn topological_order_respects_every_edge() {
127        let edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)];
128        let g = Graph::from_unweighted_edges(6, &edges, true).unwrap();
129        let order = topological_sort(&g).unwrap();
130        let position: Vec<usize> = (0..6).map(|v| order.iter().position(|&o| o == v).unwrap()).collect();
131        assert!(edges.iter().all(|&(u, v)| position[u] < position[v]));
132        assert_eq!(order, vec![4, 5, 0, 2, 3, 1]);
133        assert!(topological_sort(&Graph::from_unweighted_edges(2, &[(0, 1), (1, 0)], true).unwrap()).is_err());
134        assert!(topological_sort(&Graph::new(2, false)).is_err());
135    }
136
137    #[test]
138    fn components_and_condensation() {
139        // Components {0, 1, 2}, {3, 4}, {5}, {6, 7}.
140        let g = Graph::from_unweighted_edges(8, &[(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 3), (4, 5), (6, 7), (7, 6), (6, 5)], true).unwrap();
141        let labels = strongly_connected_components(&g);
142        let same = |a: usize, b: usize| labels[a] == labels[b];
143        assert!(same(0, 1) && same(1, 2) && same(3, 4) && same(6, 7));
144        assert!(!same(0, 3) && !same(3, 5) && !same(5, 6));
145        let (_, dag) = condensation(&g);
146        assert_eq!(dag.vertex_count(), 4);
147        let order = topological_sort(&dag).unwrap();
148        assert_eq!(order.len(), 4);
149        // The sink component {5} gets label 0 (reverse topological labelling).
150        assert_eq!(labels[5], 0);
151        // A long cycle does not overflow the stack.
152        let n = 100_000;
153        let ring = Graph::from_unweighted_edges(n, &(0..n).map(|i| (i, (i + 1) % n)).collect::<Vec<_>>(), true).unwrap();
154        assert!(strongly_connected_components(&ring).iter().all(|&c| c == 0));
155    }
156}