Skip to main content

lib_jsl_graph/
graph.rs

1//! Graph representation: adjacency lists with conversions to edge lists and matrices, traversal,
2//! connected components and a disjoint-set (union-find) structure.
3//!
4//! See the book entry [Graphs, traversal and orderings](https://jwkunz.github.io/lib_jsl/book/graph/traversal.html).
5
6use lib_jsl_core::ErrorsJSL;
7use std::collections::VecDeque;
8
9/// A weighted edge `from → to` (both directions for undirected graphs).
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct Edge {
12    pub from: usize,
13    pub to: usize,
14    pub weight: f64,
15}
16
17/// A weighted graph on vertices `0..n` stored as adjacency lists. Undirected graphs store each
18/// edge in both lists; [`Graph::edges`] reports it once.
19#[derive(Debug, Clone, PartialEq)]
20pub struct Graph {
21    directed: bool,
22    adjacency: Vec<Vec<(usize, f64)>>,
23}
24
25impl Graph {
26    /// A graph with `n` vertices and no edges.
27    pub fn new(n: usize, directed: bool) -> Self {
28        Graph { directed, adjacency: vec![Vec::new(); n] }
29    }
30
31    /// A graph from `(from, to, weight)` triples.
32    pub fn from_edges(n: usize, edges: &[(usize, usize, f64)], directed: bool) -> Result<Self, ErrorsJSL> {
33        let mut g = Graph::new(n, directed);
34        for &(u, v, w) in edges {
35            g.add_edge(u, v, w)?;
36        }
37        Ok(g)
38    }
39
40    /// A graph from unweighted `(from, to)` pairs (weight 1).
41    pub fn from_unweighted_edges(n: usize, edges: &[(usize, usize)], directed: bool) -> Result<Self, ErrorsJSL> {
42        Self::from_edges(n, &edges.iter().map(|&(u, v)| (u, v, 1.0)).collect::<Vec<_>>(), directed)
43    }
44
45    /// A graph from a square adjacency matrix: entry `(i, j)` is the weight of `i → j`, and `None`
46    /// or a NaN entry means no edge. Undirected graphs read the upper triangle.
47    pub fn from_adjacency_matrix(matrix: &[Vec<Option<f64>>], directed: bool) -> Result<Self, ErrorsJSL> {
48        let n = matrix.len();
49        if matrix.iter().any(|row| row.len() != n) {
50            return Err(ErrorsJSL::InvalidInputRange("The adjacency matrix must be square."));
51        }
52        let mut g = Graph::new(n, directed);
53        for (i, row) in matrix.iter().enumerate() {
54            for (j, entry) in row.iter().enumerate().skip(if directed { 0 } else { i }) {
55                if let Some(w) = *entry
56                    && !w.is_nan()
57                {
58                    g.add_edge(i, j, w)?;
59                }
60            }
61        }
62        Ok(g)
63    }
64
65    pub fn add_edge(&mut self, from: usize, to: usize, weight: f64) -> Result<(), ErrorsJSL> {
66        let n = self.adjacency.len();
67        if from >= n || to >= n {
68            return Err(ErrorsJSL::InvalidInputRange("Edge endpoint out of range."));
69        }
70        self.adjacency[from].push((to, weight));
71        if !self.directed && from != to {
72            self.adjacency[to].push((from, weight));
73        }
74        Ok(())
75    }
76
77    pub fn vertex_count(&self) -> usize {
78        self.adjacency.len()
79    }
80
81    pub fn is_directed(&self) -> bool {
82        self.directed
83    }
84
85    /// The out-neighbours of `v` with edge weights.
86    pub fn neighbors(&self, v: usize) -> &[(usize, f64)] {
87        &self.adjacency[v]
88    }
89
90    /// The out-degree of `v` (the degree for undirected graphs).
91    pub fn degree(&self, v: usize) -> usize {
92        self.adjacency[v].len()
93    }
94
95    /// Every edge once.
96    pub fn edges(&self) -> Vec<Edge> {
97        let mut out = Vec::new();
98        for (u, list) in self.adjacency.iter().enumerate() {
99            for &(v, w) in list {
100                if self.directed || u <= v {
101                    out.push(Edge { from: u, to: v, weight: w });
102                }
103            }
104        }
105        out
106    }
107
108    pub fn edge_count(&self) -> usize {
109        self.edges().len()
110    }
111
112    /// The adjacency matrix (`None` where there is no edge; the smallest weight for parallel
113    /// edges).
114    pub fn adjacency_matrix(&self) -> Vec<Vec<Option<f64>>> {
115        let n = self.vertex_count();
116        let mut m = vec![vec![None; n]; n];
117        for (u, list) in self.adjacency.iter().enumerate() {
118            for &(v, w) in list {
119                m[u][v] = Some(m[u][v].map_or(w, |old: f64| old.min(w)));
120            }
121        }
122        m
123    }
124
125    /// The graph with every edge reversed (itself for undirected graphs).
126    pub fn reversed(&self) -> Graph {
127        if !self.directed {
128            return self.clone();
129        }
130        let mut g = Graph::new(self.vertex_count(), true);
131        for e in self.edges() {
132            g.adjacency[e.to].push((e.from, e.weight));
133        }
134        g
135    }
136
137    /// Vertices reachable from `source` in breadth-first order.
138    pub fn breadth_first(&self, source: usize) -> Vec<usize> {
139        let mut seen = vec![false; self.vertex_count()];
140        let mut order = Vec::new();
141        let mut queue = VecDeque::from([source]);
142        seen[source] = true;
143        while let Some(u) = queue.pop_front() {
144            order.push(u);
145            for &(v, _) in &self.adjacency[u] {
146                if !seen[v] {
147                    seen[v] = true;
148                    queue.push_back(v);
149                }
150            }
151        }
152        order
153    }
154
155    /// Vertices reachable from `source` in depth-first (preorder), visiting neighbours in
156    /// insertion order; iterative, so deep graphs do not overflow the stack.
157    pub fn depth_first(&self, source: usize) -> Vec<usize> {
158        let mut seen = vec![false; self.vertex_count()];
159        let mut order = Vec::new();
160        let mut stack = vec![source];
161        while let Some(u) = stack.pop() {
162            if seen[u] {
163                continue;
164            }
165            seen[u] = true;
166            order.push(u);
167            for &(v, _) in self.adjacency[u].iter().rev() {
168                if !seen[v] {
169                    stack.push(v);
170                }
171            }
172        }
173        order
174    }
175
176    /// The component label of every vertex (weakly connected components for directed graphs),
177    /// labels numbered from 0 in order of first appearance.
178    pub fn connected_components(&self) -> Vec<usize> {
179        let mut sets = UnionFind::new(self.vertex_count());
180        for e in self.edges() {
181            sets.union(e.from, e.to);
182        }
183        let mut label = vec![usize::MAX; self.vertex_count()];
184        let mut next = 0;
185        (0..self.vertex_count())
186            .map(|v| {
187                let root = sets.find(v);
188                if label[root] == usize::MAX {
189                    label[root] = next;
190                    next += 1;
191                }
192                label[root]
193            })
194            .collect()
195    }
196}
197
198/// A disjoint-set forest with union by rank and path halving (near-constant amortised time).
199#[derive(Debug, Clone)]
200pub struct UnionFind {
201    parent: Vec<usize>,
202    rank: Vec<u8>,
203    sets: usize,
204}
205
206impl UnionFind {
207    pub fn new(n: usize) -> Self {
208        UnionFind { parent: (0..n).collect(), rank: vec![0; n], sets: n }
209    }
210
211    /// The representative of `x`'s set.
212    // ANCHOR: union_find
213    pub fn find(&mut self, mut x: usize) -> usize {
214        while self.parent[x] != x {
215            self.parent[x] = self.parent[self.parent[x]];
216            x = self.parent[x];
217        }
218        x
219    }
220
221    /// Merges the sets of `a` and `b`; returns false if they were already joined.
222    pub fn union(&mut self, a: usize, b: usize) -> bool {
223        let (ra, rb) = (self.find(a), self.find(b));
224        if ra == rb {
225            return false;
226        }
227        let (high, low) = if self.rank[ra] >= self.rank[rb] { (ra, rb) } else { (rb, ra) };
228        self.parent[low] = high;
229        if self.rank[high] == self.rank[low] {
230            self.rank[high] += 1;
231        }
232        self.sets -= 1;
233        true
234    }
235    // ANCHOR_END: union_find
236
237    pub fn connected(&mut self, a: usize, b: usize) -> bool {
238        self.find(a) == self.find(b)
239    }
240
241    /// The number of disjoint sets.
242    pub fn set_count(&self) -> usize {
243        self.sets
244    }
245}
246
247
248/// `f64` ordered by `total_cmp`, for priority queues.
249#[derive(PartialEq, Clone, Copy)]
250pub(crate) struct OrdF64(pub(crate) f64);
251impl Eq for OrdF64 {}
252impl PartialOrd for OrdF64 {
253    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
254        Some(self.cmp(other))
255    }
256}
257impl Ord for OrdF64 {
258    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
259        self.0.total_cmp(&other.0)
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn representations_convert_consistently() {
269        let g = Graph::from_edges(4, &[(0, 1, 2.0), (1, 2, 3.0), (2, 0, 1.5), (3, 3, 0.5)], false).unwrap();
270        assert_eq!(g.edge_count(), 4);
271        assert_eq!(g.degree(0), 2);
272        let m = g.adjacency_matrix();
273        assert_eq!((m[1][0], m[0][1], m[0][3], m[3][3]), (Some(2.0), Some(2.0), None, Some(0.5)));
274        assert_eq!(Graph::from_adjacency_matrix(&m, false).unwrap().edges(), g.edges());
275        let d = Graph::from_unweighted_edges(3, &[(0, 1), (1, 2)], true).unwrap();
276        assert_eq!(d.reversed().neighbors(2), &[(1, 1.0)]);
277        assert!(d.neighbors(2).is_empty());
278        assert!(Graph::from_edges(2, &[(0, 2, 1.0)], true).is_err());
279    }
280
281    #[test]
282    fn traversal_components_and_union_find() {
283        // Two components: a path 0-1-2-3 with a chord, and the pair 4-5.
284        let g = Graph::from_unweighted_edges(6, &[(0, 1), (1, 2), (2, 3), (0, 2), (4, 5)], false).unwrap();
285        assert_eq!(g.breadth_first(0), vec![0, 1, 2, 3]);
286        assert_eq!(g.depth_first(0), vec![0, 1, 2, 3]);
287        assert_eq!(g.connected_components(), vec![0, 0, 0, 0, 1, 1]);
288        let mut sets = UnionFind::new(5);
289        assert!(sets.union(0, 1) && sets.union(3, 4) && !sets.union(1, 0));
290        assert!(sets.connected(0, 1) && !sets.connected(1, 3) && sets.set_count() == 3);
291        // A long path does not overflow the traversal stack.
292        let n = 200_000;
293        let path = Graph::from_unweighted_edges(n, &(0..n - 1).map(|i| (i, i + 1)).collect::<Vec<_>>(), true).unwrap();
294        assert_eq!(path.depth_first(0).len(), n);
295    }
296}