Skip to main content

lib_jsl_graph/
all_pairs.rs

1//! All-pairs shortest paths by the Floyd-Warshall algorithm and by Johnson's algorithm.
2//!
3//! See the book entry [Shortest paths](https://jwkunz.github.io/lib_jsl/book/graph/shortest-paths.html#floydwarshall).
4
5use crate::graph::Graph;
6use crate::graph::OrdF64;
7use lib_jsl_core::ErrorsJSL;
8
9/// The all-pairs distance matrix and the successor matrix for path reconstruction.
10#[derive(Debug, Clone, PartialEq)]
11pub struct AllPairsShortestPaths {
12    /// `distance[i][j]`, `f64::INFINITY` when `j` is unreachable from `i`.
13    pub distance: Vec<Vec<f64>>,
14    next: Vec<Vec<Option<usize>>>,
15}
16
17impl AllPairsShortestPaths {
18    /// The vertices of a shortest path from `i` to `j`, or `None` if unreachable.
19    pub fn path(&self, i: usize, j: usize) -> Option<Vec<usize>> {
20        if i == j {
21            return Some(vec![i]);
22        }
23        let mut path = vec![i];
24        let mut v = i;
25        while v != j {
26            v = self.next[v][j]?;
27            path.push(v);
28        }
29        Some(path)
30    }
31}
32
33/// Floyd-Warshall, `O(V³)` time and `O(V²)` memory; negative edges are allowed. Returns an error
34/// if the graph has a negative cycle (a negative diagonal entry).
35pub fn floyd_warshall(g: &Graph) -> Result<AllPairsShortestPaths, ErrorsJSL> {
36    let n = g.vertex_count();
37    let mut distance = vec![vec![f64::INFINITY; n]; n];
38    let mut next = vec![vec![None; n]; n];
39    for (i, row) in distance.iter_mut().enumerate() {
40        row[i] = 0.0;
41        next[i][i] = Some(i);
42    }
43    for e in g.edges() {
44        for (u, v) in if g.is_directed() { vec![(e.from, e.to)] } else { vec![(e.from, e.to), (e.to, e.from)] } {
45            if e.weight < distance[u][v] {
46                distance[u][v] = e.weight;
47                next[u][v] = Some(v);
48            }
49        }
50    }
51    // ANCHOR: floyd
52    for k in 0..n {
53        for i in 0..n {
54            let dik = distance[i][k];
55            if !dik.is_finite() {
56                continue;
57            }
58            for j in 0..n {
59                let candidate = dik + distance[k][j];
60                if candidate < distance[i][j] {
61                    distance[i][j] = candidate;
62                    next[i][j] = next[i][k];
63                }
64            }
65        }
66    }
67    // ANCHOR_END: floyd
68    if (0..n).any(|i| distance[i][i] < 0.0) {
69        return Err(ErrorsJSL::RuntimeError("The graph contains a negative cycle."));
70    }
71    Ok(AllPairsShortestPaths { distance, next })
72}
73
74// ANCHOR: johnson
75/// Johnson's algorithm (SciPy's `johnson`), `O(V E log V)`, better than Floyd-Warshall on sparse
76/// graphs and allowing negative edges. Bellman-Ford from an added vertex joined to every vertex
77/// by a zero edge gives potentials `h` with `w(u, v) + h(u) − h(v) ≥ 0`; Dijkstra from every
78/// vertex on these reweighted edges, which keeps shortest paths shortest, then gives the
79/// distances `d'(u, v) − h(u) + h(v)`. Errors on a negative cycle (any negative edge of an
80/// undirected graph is one).
81pub fn johnson(g: &Graph) -> Result<AllPairsShortestPaths, ErrorsJSL> {
82    let n = g.vertex_count();
83    let edges = g.edges();
84    let arcs: Vec<(usize, usize, f64)> = edges
85        .iter()
86        .flat_map(|e| if g.is_directed() { vec![(e.from, e.to, e.weight)] } else { vec![(e.from, e.to, e.weight), (e.to, e.from, e.weight)] })
87        .collect();
88    if arcs.iter().any(|a| a.2.is_nan()) {
89        return Err(ErrorsJSL::InvalidInputRange("johnson: edge weights must not be NaN"));
90    }
91    // Potentials: Bellman-Ford from a virtual source at distance 0 from everything.
92    let mut h = vec![0.0f64; n];
93    let mut changed = true;
94    for _ in 0..=n {
95        changed = false;
96        for &(u, v, w) in &arcs {
97            if h[u] + w < h[v] {
98                h[v] = h[u] + w;
99                changed = true;
100            }
101        }
102        if !changed {
103            break;
104        }
105    }
106    if changed {
107        return Err(ErrorsJSL::RuntimeError("The graph contains a negative cycle."));
108    }
109    let mut adj: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
110    for &(u, v, w) in &arcs {
111        adj[u].push((v, (w + h[u] - h[v]).max(0.0)));
112    }
113    let mut distance = vec![vec![f64::INFINITY; n]; n];
114    let mut next = vec![vec![None; n]; n];
115    for s in 0..n {
116        let mut dist = vec![f64::INFINITY; n];
117        let mut pred: Vec<Option<usize>> = vec![None; n];
118        dist[s] = 0.0;
119        let mut heap = std::collections::BinaryHeap::new();
120        heap.push(std::cmp::Reverse((OrdF64(0.0), s)));
121        while let Some(std::cmp::Reverse((OrdF64(d), u))) = heap.pop() {
122            if d > dist[u] {
123                continue;
124            }
125            for &(v, w) in &adj[u] {
126                if d + w < dist[v] {
127                    dist[v] = d + w;
128                    pred[v] = Some(u);
129                    heap.push(std::cmp::Reverse((OrdF64(d + w), v)));
130                }
131            }
132        }
133        for t in 0..n {
134            if dist[t].is_finite() {
135                distance[s][t] = dist[t] - h[s] + h[t];
136                // The first step from s towards t: walk back along the predecessors.
137                let mut v = t;
138                while let Some(p) = pred[v] {
139                    if p == s {
140                        break;
141                    }
142                    v = p;
143                }
144                next[s][t] = Some(v);
145            }
146        }
147        next[s][s] = Some(s);
148    }
149    Ok(AllPairsShortestPaths { distance, next })
150}
151// ANCHOR_END: johnson
152
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use crate::shortest_paths::bellman_ford;
158
159    #[test]
160    fn matches_single_source_runs_and_reconstructs_paths() {
161        let g = Graph::from_edges(5, &[(0, 1, 6.0), (0, 3, 7.0), (1, 2, 5.0), (1, 3, 8.0), (1, 4, -4.0), (2, 1, -2.0), (3, 2, -3.0), (3, 4, 9.0), (4, 0, 2.0), (4, 2, 7.0)], true).unwrap();
162        let all = floyd_warshall(&g).unwrap();
163        for s in 0..5 {
164            assert_eq!(all.distance[s], bellman_ford(&g, s).unwrap().distance, "source {s}");
165        }
166        assert_eq!(all.path(0, 4).unwrap(), vec![0, 3, 2, 1, 4]);
167        assert_eq!(all.path(2, 2).unwrap(), vec![2]);
168        let split = floyd_warshall(&Graph::from_edges(3, &[(0, 1, 1.0)], false).unwrap()).unwrap();
169        assert!(split.path(0, 2).is_none() && split.distance[1][0] == 1.0);
170        assert!(floyd_warshall(&Graph::from_edges(2, &[(0, 1, -1.0), (1, 0, -1.0)], true).unwrap()).is_err());
171    }
172
173    #[test]
174    fn johnson_agrees_with_floyd_warshall() {
175        let g = Graph::from_edges(5, &[(0, 1, 6.0), (0, 3, 7.0), (1, 2, 5.0), (1, 3, 8.0), (1, 4, -4.0), (2, 1, -2.0), (3, 2, -3.0), (3, 4, 9.0), (4, 0, 2.0), (4, 2, 7.0)], true).unwrap();
176        let (a, b) = (johnson(&g).unwrap(), floyd_warshall(&g).unwrap());
177        for i in 0..5 {
178            for j in 0..5 {
179                assert!((a.distance[i][j] - b.distance[i][j]).abs() < 1e-12);
180                let p = a.path(i, j).unwrap();
181                let len: f64 = p.windows(2).map(|w| g.neighbors(w[0]).iter().filter(|e| e.0 == w[1]).map(|e| e.1).fold(f64::INFINITY, f64::min)).sum();
182                assert!((len - a.distance[i][j]).abs() < 1e-12);
183            }
184        }
185        assert!(johnson(&Graph::from_edges(2, &[(0, 1, -1.0)], false).unwrap()).is_err());
186    }
187}