hypergraph_rs/algorithms/
shortest_path.rs1use std::collections::VecDeque;
8
9use indexmap::IndexMap;
10
11use crate::Hypergraph;
12
13pub 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 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
43pub 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}