Skip to main content

hypergraph_rs/algorithms/
shortest_path.rs

1//! Unit-hop shortest paths on a hypergraph (`xgi/algorithms/shortest_path.py`).
2//!
3//! XGI's Dijkstra uses a fixed increment of 1 per hop, i.e. BFS levels over the
4//! node-neighbour relation. We hand-roll that BFS (unit-weight exact parity;
5//! keeps the algorithm independent of the rustworkx-core `dijkstra` return type).
6
7use std::collections::VecDeque;
8
9use indexmap::IndexMap;
10
11use crate::Hypergraph;
12
13/// Distances from `source` to every node (unit hops). Unreachable nodes get
14/// `f64::INFINITY`; `source` gets `0`. Keys in `node_ids()` order. `None` if
15/// `source` is absent. XGI parity: `single_source_shortest_path_length`.
16pub fn single_source_shortest_path_length<N, E, M>(
17    h: &Hypergraph<N, E, M>,
18    source: &str,
19) -> Option<IndexMap<String, f64>> {
20    if !h.has_node(source) {
21        return None;
22    }
23    let mut dist: IndexMap<String, f64> = IndexMap::new();
24    for n in h.node_ids() {
25        dist.insert(n, f64::INFINITY);
26    }
27    dist.insert(source.to_string(), 0.0);
28    let mut queue: VecDeque<String> = VecDeque::new();
29    queue.push_back(source.to_string());
30    // Bounded: each node is enqueued at most once (distance set from INF once).
31    while let Some(cur) = queue.pop_front() {
32        let cur_d = dist[&cur];
33        for nb in h.node_neighbors(&cur).unwrap_or_default() {
34            if dist[&nb].is_infinite() {
35                dist.insert(nb.clone(), cur_d + 1.0);
36                queue.push_back(nb);
37            }
38        }
39    }
40    Some(dist)
41}
42
43/// Distances from every source. XGI parity: `shortest_path_length`.
44pub fn shortest_path_length<N, E, M>(
45    h: &Hypergraph<N, E, M>,
46) -> Vec<(String, IndexMap<String, f64>)> {
47    h.node_ids()
48        .into_iter()
49        .filter_map(|src| single_source_shortest_path_length(h, &src).map(|d| (src, d)))
50        .collect()
51}