Skip to main content

lib_jsl_graph/
k_shortest.rs

1//! The `K` shortest loopless paths between two vertices by Yen's algorithm (SciPy's `yen`).
2//!
3//! See the book entry [Matchings, k shortest paths and Laplacians](https://jwkunz.github.io/lib_jsl/book/graph/matching-laplacian.html#yens-k-shortest-paths).
4
5use crate::graph::Graph;
6use crate::graph::OrdF64;
7use lib_jsl_core::ErrorsJSL;
8use std::cmp::Reverse;
9use std::collections::{BinaryHeap, HashSet};
10
11
12/// Dijkstra from `s` to `t` avoiding the vertices in `blocked_v` and the arcs in `blocked_e`.
13fn restricted_path(g: &Graph, s: usize, t: usize, blocked_v: &[bool], blocked_e: &HashSet<(usize, usize)>) -> Option<(f64, Vec<usize>)> {
14    let n = g.vertex_count();
15    let mut dist = vec![f64::INFINITY; n];
16    let mut pred: Vec<Option<usize>> = vec![None; n];
17    dist[s] = 0.0;
18    let mut heap = BinaryHeap::from([Reverse((OrdF64(0.0), s))]);
19    while let Some(Reverse((OrdF64(d), u))) = heap.pop() {
20        if d > dist[u] {
21            continue;
22        }
23        if u == t {
24            break;
25        }
26        for &(v, w) in g.neighbors(u) {
27            if blocked_v[v] || blocked_e.contains(&(u, v)) {
28                continue;
29            }
30            if d + w < dist[v] {
31                dist[v] = d + w;
32                pred[v] = Some(u);
33                heap.push(Reverse((OrdF64(d + w), v)));
34            }
35        }
36    }
37    if !dist[t].is_finite() {
38        return None;
39    }
40    let mut path = vec![t];
41    let mut v = t;
42    while let Some(p) = pred[v] {
43        path.push(p);
44        v = p;
45    }
46    path.reverse();
47    Some((dist[t], path))
48}
49
50fn arc_weight(g: &Graph, u: usize, v: usize) -> f64 {
51    g.neighbors(u).iter().filter(|e| e.0 == v).map(|e| e.1).fold(f64::INFINITY, f64::min)
52}
53
54// ANCHOR: yen
55/// The `k` shortest loopless paths from `source` to `sink`, shortest first, as
56/// `(length, vertices)` (SciPy's `yen`). Yen's algorithm takes each path found so far and, for
57/// every vertex on it (the spur), finds the shortest path from the spur that leaves the common
58/// prefix differently from every path already found, avoiding the prefix's vertices; the best of
59/// these candidates is the next path. Weights must be non-negative. Fewer than `k` paths are
60/// returned if fewer exist.
61pub fn yen(g: &Graph, source: usize, sink: usize, k: usize) -> Result<Vec<(f64, Vec<usize>)>, ErrorsJSL> {
62    let n = g.vertex_count();
63    if source >= n || sink >= n {
64        return Err(ErrorsJSL::InvalidInputRange("yen: vertex out of range"));
65    }
66    if g.edges().iter().any(|e| e.weight.is_nan() || e.weight < 0.0) {
67        return Err(ErrorsJSL::InvalidInputRange("yen: weights must be non-negative"));
68    }
69    let mut found: Vec<(f64, Vec<usize>)> = Vec::new();
70    if k == 0 {
71        return Ok(found);
72    }
73    let none = vec![false; n];
74    match restricted_path(g, source, sink, &none, &HashSet::new()) {
75        Some(p) => found.push(p),
76        None => return Ok(found),
77    }
78    let mut candidates: Vec<(f64, Vec<usize>)> = Vec::new();
79    while found.len() < k {
80        let last = found.last().expect("non-empty").1.clone();
81        for i in 0..last.len() - 1 {
82            let spur = last[i];
83            let root = &last[..=i];
84            let mut blocked_e = HashSet::new();
85            for (_, p) in &found {
86                if p.len() > i && &p[..=i] == root {
87                    blocked_e.insert((p[i], p[i + 1]));
88                    if !g.is_directed() {
89                        blocked_e.insert((p[i + 1], p[i]));
90                    }
91                }
92            }
93            let mut blocked_v = vec![false; n];
94            for &v in &root[..i] {
95                blocked_v[v] = true;
96            }
97            if let Some((_, spur_path)) = restricted_path(g, spur, sink, &blocked_v, &blocked_e) {
98                let mut path = root[..i].to_vec();
99                path.extend(spur_path);
100                let cost: f64 = path.windows(2).map(|w| arc_weight(g, w[0], w[1])).sum();
101                if !candidates.iter().any(|c| c.1 == path) && !found.iter().any(|c| c.1 == path) {
102                    candidates.push((cost, path));
103                }
104            }
105        }
106        if candidates.is_empty() {
107            break;
108        }
109        // The cheapest candidate; ties to the one with fewer vertices, then the first found.
110        let best = (0..candidates.len())
111            .min_by(|&a, &b| candidates[a].0.total_cmp(&candidates[b].0).then(candidates[a].1.len().cmp(&candidates[b].1.len())))
112            .expect("non-empty");
113        found.push(candidates.remove(best));
114    }
115    Ok(found)
116}
117// ANCHOR_END: yen
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn wikipedia_example() {
125        // Vertices C, D, E, F, G, H as 0..6; the three shortest C → H paths have lengths 5, 7, 8.
126        let g = Graph::from_edges(6, &[(0, 1, 3.0), (0, 2, 2.0), (1, 3, 4.0), (2, 1, 1.0), (2, 3, 2.0), (2, 4, 3.0), (3, 4, 2.0), (3, 5, 1.0), (4, 5, 2.0)], true).unwrap();
127        let p = yen(&g, 0, 5, 3).unwrap();
128        let lengths: Vec<f64> = p.iter().map(|x| x.0).collect();
129        assert_eq!(lengths, vec![5.0, 7.0, 8.0]);
130        assert_eq!(p[0].1, vec![0, 2, 3, 5]);
131        // All loopless.
132        for (_, path) in &p {
133            let set: HashSet<_> = path.iter().collect();
134            assert_eq!(set.len(), path.len());
135        }
136        assert_eq!(yen(&g, 0, 5, 100).unwrap().len(), 7);
137    }
138}