pathfinding/directed/bfs.rs
1//! Compute a shortest path using the [breadth-first search
2//! algorithm](https://en.wikipedia.org/wiki/Breadth-first_search).
3
4use super::reverse_path;
5use crate::{FxIndexMap, FxIndexSet, NodeRefs};
6use indexmap::map::Entry::Vacant;
7use std::hash::Hash;
8use std::iter::FusedIterator;
9
10/// Compute a shortest path using the [breadth-first search
11/// algorithm](https://en.wikipedia.org/wiki/Breadth-first_search).
12///
13/// The shortest path starting from `start` up to a node for which `success` returns `true` is
14/// computed and returned in a `Some`. If no path can be found, `None`
15/// is returned instead.
16///
17/// - `start` is the starting node.
18/// - `successors` returns a list of successors for a given node.
19/// - `success` checks whether the goal has been reached. It is not a node as some problems require
20/// a dynamic solution instead of a fixed node.
21///
22/// A node will never be included twice in the path as determined by the `Eq` relationship.
23///
24/// The returned path comprises both the start and end node.
25///
26/// # Example
27///
28/// We will search the shortest path on a chess board to go from (1, 1) to (4, 6) doing only knight
29/// moves.
30///
31/// The first version uses an explicit type `Pos` on which the required traits are derived.
32///
33/// ```
34/// use pathfinding::prelude::bfs;
35///
36/// #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
37/// struct Pos(i32, i32);
38///
39/// impl Pos {
40/// fn successors(&self) -> Vec<Pos> {
41/// let &Pos(x, y) = self;
42/// vec![Pos(x+1,y+2), Pos(x+1,y-2), Pos(x-1,y+2), Pos(x-1,y-2),
43/// Pos(x+2,y+1), Pos(x+2,y-1), Pos(x-2,y+1), Pos(x-2,y-1)]
44/// }
45/// }
46///
47/// static GOAL: Pos = Pos(4, 6);
48/// let result = bfs(&Pos(1, 1), |p| p.successors(), |p| *p == GOAL);
49/// assert_eq!(result.expect("no path found").len(), 5);
50/// ```
51///
52/// The second version does not declare a `Pos` type, makes use of more closures,
53/// and is thus shorter.
54///
55/// ```
56/// use pathfinding::prelude::bfs;
57///
58/// static GOAL: (i32, i32) = (4, 6);
59/// let result = bfs(&(1, 1),
60/// |&(x, y)| vec![(x+1,y+2), (x+1,y-2), (x-1,y+2), (x-1,y-2),
61/// (x+2,y+1), (x+2,y-1), (x-2,y+1), (x-2,y-1)],
62/// |&p| p == GOAL);
63/// assert_eq!(result.expect("no path found").len(), 5);
64/// ```
65pub fn bfs<'a, N, S, FN, IN, FS>(start: S, successors: FN, success: FS) -> Option<Vec<N>>
66where
67 N: Eq + Hash + Clone + 'a,
68 S: Into<NodeRefs<'a, N>>,
69 FN: FnMut(&N) -> IN,
70 IN: IntoIterator<Item = N>,
71 FS: FnMut(&N) -> bool,
72{
73 bfs_core(&start.into(), successors, success, true)
74}
75
76fn bfs_core<'a, N, FN, IN, FS>(
77 start: &NodeRefs<'a, N>,
78 mut successors: FN,
79 mut success: FS,
80 check_first: bool,
81) -> Option<Vec<N>>
82where
83 N: Eq + Hash + Clone + 'a,
84 FN: FnMut(&N) -> IN,
85 IN: IntoIterator<Item = N>,
86 FS: FnMut(&N) -> bool,
87{
88 if check_first {
89 for start_node in start {
90 if success(start_node) {
91 return Some(vec![start_node.clone()]);
92 }
93 }
94 }
95
96 let mut parents: FxIndexMap<N, usize> = FxIndexMap::default();
97 parents.extend(start.into_iter().map(|n| (n.clone(), usize::MAX)));
98
99 let mut i = 0;
100 while let Some((node, _)) = parents.get_index(i) {
101 for successor in successors(node) {
102 if success(&successor) {
103 let mut path = reverse_path(&parents, |&p| p, i);
104 path.push(successor);
105 return Some(path);
106 }
107 if let Vacant(e) = parents.entry(successor) {
108 e.insert(i);
109 }
110 }
111 i += 1;
112 }
113 None
114}
115
116/// Return one of the shortest loop from start to start if it exists, `None` otherwise.
117///
118/// - `start` is the starting node.
119/// - `successors` returns a list of successors for a given node.
120///
121/// Except the start node which will be included both at the beginning and the end of
122/// the path, a node will never be included twice in the path as determined
123/// by the `Eq` relationship.
124pub fn bfs_loop<'a, N, S, FN, IN>(start: S, successors: FN) -> Option<Vec<N>>
125where
126 N: Eq + Hash + Clone + 'a,
127 S: Into<NodeRefs<'a, N>>,
128 FN: FnMut(&N) -> IN,
129 IN: IntoIterator<Item = N>,
130{
131 let start = start.into();
132 bfs_core(&start, successors, |n| start.contains(n), false)
133}
134
135/// Compute a shortest path using the [breadth-first search
136/// algorithm](https://en.wikipedia.org/wiki/Breadth-first_search) with
137/// [bidirectional search](https://en.wikipedia.org/wiki/Bidirectional_search).
138///
139/// Bidirectional search runs two simultaneous searches: one forward from the start,
140/// and one backward from the end, stopping when the two meet. In many cases this gives
141/// a faster result than searching only in a single direction.
142///
143/// The shortest path starting from `start` up to a node `end` is
144/// computed and returned in a `Some`. If no path can be found, `None`
145/// is returned instead.
146///
147/// - `start` is the starting node.
148/// - `end` is the end node.
149/// - `successors_fn` returns a list of successors for a given node.
150/// - `predecessors_fn` returns a list of predecessors for a given node. For an undirected graph
151/// this will be the same as `successors_fn`, however for a directed graph this will be different.
152///
153/// A node will never be included twice in the path as determined by the `Eq` relationship.
154///
155/// The returned path comprises both the start and end node.
156///
157/// # Example
158///
159/// We will search the shortest path on a chess board to go from (1, 1) to (4, 6) doing only knight
160/// moves.
161///
162/// ```
163/// use pathfinding::prelude::bfs_bidirectional;
164///
165/// static SUCCESSORS: fn(&(i32, i32)) -> Vec<(i32, i32)> = |&(x, y)| vec![
166/// (x+1,y+2), (x+1,y-2), (x-1,y+2), (x-1,y-2),
167/// (x+2,y+1), (x+2,y-1), (x-2,y+1), (x-2,y-1)
168/// ];
169/// let result = bfs_bidirectional(&(1, 1), &(4, 6), SUCCESSORS, SUCCESSORS);
170/// assert_eq!(result.expect("no path found").len(), 5);
171/// ```
172///
173/// Find also a more interesting example, comparing regular
174/// and bidirectional BFS [here](https://github.com/evenfurther/pathfinding/blob/main/examples/bfs_bidirectional.rs).
175#[expect(clippy::missing_panics_doc)]
176pub fn bfs_bidirectional<'a, N, S, E, FNS, FNP, IN>(
177 start: S,
178 end: E,
179 successors_fn: FNS,
180 predecessors_fn: FNP,
181) -> Option<Vec<N>>
182where
183 N: Eq + Hash + Clone + 'a,
184 E: Into<NodeRefs<'a, N>>,
185 S: Into<NodeRefs<'a, N>>,
186 FNS: Fn(&N) -> IN,
187 FNP: Fn(&N) -> IN,
188 IN: IntoIterator<Item = N>,
189{
190 let start = start.into();
191 let end = end.into();
192
193 let mut predecessors: FxIndexMap<N, Option<usize>> = FxIndexMap::default();
194 predecessors.extend(start.into_iter().cloned().map(|n| (n, None)));
195 let mut successors: FxIndexMap<N, Option<usize>> = FxIndexMap::default();
196 successors.extend(end.into_iter().cloned().map(|n| (n, None)));
197
198 let mut i_forwards = 0;
199 let mut i_backwards = 0;
200 let middle = 'l: loop {
201 for _ in 0..(predecessors.len() - i_forwards) {
202 let node = predecessors.get_index(i_forwards).unwrap().0;
203 for successor_node in successors_fn(node) {
204 if !predecessors.contains_key(&successor_node) {
205 predecessors.insert(successor_node.clone(), Some(i_forwards));
206 }
207 if successors.contains_key(&successor_node) {
208 break 'l Some(successor_node);
209 }
210 }
211 i_forwards += 1;
212 }
213
214 for _ in 0..(successors.len() - i_backwards) {
215 let node = successors.get_index(i_backwards).unwrap().0;
216 for predecessor_node in predecessors_fn(node) {
217 if !successors.contains_key(&predecessor_node) {
218 successors.insert(predecessor_node.clone(), Some(i_backwards));
219 }
220 if predecessors.contains_key(&predecessor_node) {
221 break 'l Some(predecessor_node);
222 }
223 }
224 i_backwards += 1;
225 }
226
227 if i_forwards == predecessors.len() && i_backwards == successors.len() {
228 break 'l None;
229 }
230 };
231
232 middle.map(|middle| {
233 // Path found!
234 // Build the path.
235 let mut path = vec![];
236 // From middle to the start.
237 let mut node = Some(middle.clone());
238 while let Some(n) = node {
239 path.push(n.clone());
240 node = predecessors[&n].map(|i| predecessors.get_index(i).unwrap().0.clone());
241 }
242 // Reverse, to put start at the front.
243 path.reverse();
244 // And from middle to the end.
245 let mut node = successors[&middle].map(|i| successors.get_index(i).unwrap().0.clone());
246 while let Some(n) = node {
247 path.push(n.clone());
248 node = successors[&n].map(|i| successors.get_index(i).unwrap().0.clone());
249 }
250 path
251 })
252}
253
254/// Visit all nodes that are reachable from a start node. The node will be visited
255/// in BFS order, starting from the `start` node and following the order returned
256/// by the `successors` function.
257///
258/// # Examples
259///
260/// The iterator stops when there are no new nodes to visit:
261///
262/// ```
263/// use pathfinding::prelude::bfs_reach;
264///
265/// let all_nodes = bfs_reach(3, |_| (1..=5)).collect::<Vec<_>>();
266/// assert_eq!(all_nodes, vec![3, 1, 2, 4, 5]);
267/// ```
268///
269/// The iterator can be used as a generator. Here are for examples
270/// the multiples of 2 and 3 (although not in natural order but in
271/// the order they are discovered by the BFS algorithm):
272///
273/// ```
274/// use pathfinding::prelude::bfs_reach;
275///
276/// let mut it = bfs_reach(1, |&n| vec![n*2, n*3]).skip(1);
277/// assert_eq!(it.next(), Some(2)); // 1*2
278/// assert_eq!(it.next(), Some(3)); // 1*3
279/// assert_eq!(it.next(), Some(4)); // (1*2)*2
280/// assert_eq!(it.next(), Some(6)); // (1*2)*3
281/// // (1*3)*2 == 6 which has been seen already
282/// assert_eq!(it.next(), Some(9)); // (1*3)*3
283/// assert_eq!(it.next(), Some(8)); // ((1*2)*2)*2
284/// assert_eq!(it.next(), Some(12)); // ((1*2)*2)*3
285/// ```
286pub fn bfs_reach<N, FN, IN>(start: N, successors: FN) -> BfsReachable<N, FN>
287where
288 N: Eq + Hash + Clone,
289 FN: FnMut(&N) -> IN,
290 IN: IntoIterator<Item = N>,
291{
292 let mut seen = FxIndexSet::default();
293 seen.insert(start);
294 BfsReachable {
295 i: 0,
296 seen,
297 successors,
298 }
299}
300
301/// Struct returned by [`bfs_reach`].
302pub struct BfsReachable<N, FN> {
303 i: usize,
304 seen: FxIndexSet<N>,
305 successors: FN,
306}
307
308impl<N, FN> BfsReachable<N, FN> {
309 /// Return a lower bound on the number of remaining reachable
310 /// nodes. Not all nodes are necessarily known in advance, and
311 /// new reachable nodes may be discovered while using the iterator.
312 pub fn remaining_nodes_low_bound(&self) -> usize {
313 self.seen.len() - self.i
314 }
315}
316
317impl<N, FN, IN> Iterator for BfsReachable<N, FN>
318where
319 N: Eq + Hash + Clone,
320 FN: FnMut(&N) -> IN,
321 IN: IntoIterator<Item = N>,
322{
323 type Item = N;
324
325 fn next(&mut self) -> Option<Self::Item> {
326 let n = self.seen.get_index(self.i)?.clone();
327 for s in (self.successors)(&n) {
328 self.seen.insert(s);
329 }
330 self.i += 1;
331 Some(n)
332 }
333}
334
335impl<N, FN, IN> FusedIterator for BfsReachable<N, FN>
336where
337 N: Eq + Hash + Clone,
338 FN: FnMut(&N) -> IN,
339 IN: IntoIterator<Item = N>,
340{
341}