graphity_core/bfs_distances.rs
1use crate::error::check_index;
2use crate::{Graph, NONE};
3
4/// The distances of the nodes of a graph from one or several sources, with a shortest path to every
5/// node reached.
6///
7/// The sources are the nodes where the search starts. The distance of a node is the number of edges on
8/// a shortest path to it from the nearest source. A source has distance 0, and a node that no source
9/// reaches has distance `None` - Java's `-1`. Edges are followed in their direction. For distances
10/// against their direction, pass the transposed graph: `BiAdjacentGraph::of(&graph).transposed()`.
11/// Here, `calls` are the calls between the methods of a program, and the search finds a shortest chain
12/// of calls from `main` to `parse`:
13///
14/// <!-- example: traversals.rs#pathTo -->
15/// ```
16/// # use graphity_core::BfsDistances;
17/// # let calls = graphity_core::Graph::of(
18/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
19/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
20/// # ).unwrap();
21/// # let (main, parse) = (0, 6);
22/// let from_main = BfsDistances::of(&calls, main);
23/// let depth = from_main.distance_of(parse);
24/// let chain = from_main.path_to(parse);
25/// // depth: Some(3)
26/// // chain: [0, 2, 3, 6] - main -> run -> load -> parse
27/// # assert_eq!(depth, Some(3));
28/// # assert_eq!(chain, [0, 2, 3, 6]);
29/// ```
30///
31/// Uses a [breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search) that takes the
32/// sources in list order and the out-nodes of each node in ascending order. For the reachable nodes
33/// alone, [`graphs::reachable_from_sources`](crate::graphs::reachable_from_sources) needs less memory.
34///
35/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
36///
37/// **Memory:** 8 x node_count bytes: the distance of each node and the node before it on its
38/// shortest path.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct BfsDistances {
41 /// Distance of each node from the nearest source, [`NONE`] if unreachable.
42 distance: Box<[u32]>,
43 /// Breadth-first predecessor of each node, [`NONE`] for a source and when unreachable.
44 predecessor: Box<[u32]>,
45 /// The largest finite distance, [`NONE`] if no node is reachable.
46 max_distance: u32,
47}
48
49impl BfsDistances {
50 /// Returns the distances of the nodes of `graph` from `source`. Equivalent to
51 /// [`of_sources(graph, &[source])`](Self::of_sources) - Java's overload `of(Graph, int)`.
52 ///
53 /// **Time:** O(node_count + edge_count).
54 /// **Memory:** as for [`of_sources`](Self::of_sources).
55 ///
56 /// # Panics
57 /// With an `index out of bounds` message if `source` is not in `0..node_count`.
58 #[track_caller]
59 pub fn of(graph: &Graph, source: u32) -> BfsDistances {
60 Self::of_sources(graph, &[source])
61 }
62
63 /// Returns the distances of the nodes of `graph` from the nearest of `sources` - Java's overload
64 /// `of(Graph, IntList)`.
65 ///
66 /// A source given twice counts once, and with no sources, no node is reachable.
67 ///
68 /// **Time:** O(sources.len() + node_count + edge_count).
69 /// **Memory:** 8 x node_count bytes for the result; while it runs, 4 x node_count bytes more.
70 ///
71 /// # Panics
72 /// With an `index out of bounds` message if a source is not in `0..node_count`; then no work is done.
73 #[track_caller]
74 pub fn of_sources(graph: &Graph, sources: &[u32]) -> BfsDistances {
75 let n = graph.node_count();
76 crate::error::check_nodes(sources, n);
77 let n = n as usize;
78 let out = graph.out_adjacency_start();
79 let adj = graph.out_adjacency();
80 let mut distance = vec![NONE; n];
81 let mut predecessor = vec![NONE; n];
82 let mut queue = vec![0u32; n];
83 let mut tail = 0usize;
84 for &s in sources {
85 if distance[s as usize] == NONE {
86 distance[s as usize] = 0;
87 queue[tail] = s;
88 tail += 1;
89 }
90 }
91 let mut head = 0usize;
92 while head < tail {
93 let u = queue[head] as usize;
94 head += 1;
95 let next = distance[u] + 1;
96 for &v in &adj[out[u] as usize..out[u + 1] as usize] {
97 if distance[v as usize] == NONE {
98 distance[v as usize] = next;
99 predecessor[v as usize] = u as u32;
100 queue[tail] = v;
101 tail += 1;
102 }
103 }
104 }
105 let max_distance = if tail == 0 {
106 NONE
107 } else {
108 distance[queue[tail - 1] as usize]
109 };
110 BfsDistances {
111 distance: distance.into_boxed_slice(),
112 predecessor: predecessor.into_boxed_slice(),
113 max_distance,
114 }
115 }
116
117 /// Returns the distance of `node`, or `None` if no source reaches it - Java's `-1`. The distance is
118 /// the number of edges on a shortest path to `node` from the nearest source.
119 ///
120 /// **Time:** O(1).
121 ///
122 /// # Panics
123 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
124 #[inline]
125 #[track_caller]
126 pub fn distance_of(&self, node: u32) -> Option<u32> {
127 check_index(node, self.distance.len() as u32);
128 let d = self.distance[node as usize];
129 (d != NONE).then_some(d)
130 }
131
132 /// Returns whether a source reaches `node`. Equivalent to `distance_of(node).is_some()`.
133 ///
134 /// **Time:** O(1).
135 ///
136 /// # Panics
137 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
138 #[inline]
139 #[track_caller]
140 pub fn is_reachable(&self, node: u32) -> bool {
141 self.distance_of(node).is_some()
142 }
143
144 /// Returns a shortest path to `node` from the nearest source, or an empty vector if no source reaches
145 /// `node`.
146 ///
147 /// The path has one node more than the distance of `node`, with the source first and `node` last. Of
148 /// several shortest paths, this method returns the one that the search finds first. The result is a
149 /// vector the caller owns - Java returns an unmodifiable `IntList`.
150 ///
151 /// **Time:** O(d), where d is the distance of `node`.
152 /// **Memory:** 4 x (d + 1) bytes for the result.
153 ///
154 /// # Panics
155 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
156 #[track_caller]
157 pub fn path_to(&self, node: u32) -> Vec<u32> {
158 let Some(d) = self.distance_of(node) else {
159 return Vec::new();
160 };
161 let mut path = vec![0u32; d as usize + 1];
162 let mut v = node;
163 for slot in path.iter_mut().rev() {
164 *slot = v;
165 v = self.predecessor[v as usize];
166 }
167 path
168 }
169
170 /// Returns the largest distance of a node that a source reaches, or `None` if there are no sources -
171 /// Java's `-1`.
172 ///
173 /// **Time:** O(1).
174 #[inline]
175 pub fn max_distance(&self) -> Option<u32> {
176 (self.max_distance != NONE).then_some(self.max_distance)
177 }
178}