1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
//! Compute a shortest path using the [Dijkstra search
//! algorithm](https://en.wikipedia.org/wiki/Dijkstra's_algorithm).
use std::{cmp::Ordering, collections::BinaryHeap, hash::Hash};
use brontes_types::{FastHashMap, FastHashSet, FastHasher};
use indexmap::{
map::Entry::{Occupied, Vacant},
IndexMap,
};
use pathfinding::num_traits::Zero;
type FxIndexMap<K, V> = IndexMap<K, V, FastHasher>;
const MAX_LEN: usize = 4;
const MAX_OTHER_PATHS: usize = 3;
/// Compute a shortest path using the [Dijkstra search
/// algorithm](https://en.wikipedia.org/wiki/Dijkstra's_algorithm).
///
/// The shortest path starting from `start` up to a node for which `success`
/// returns `true` is computed and returned along with its total cost, in a
/// `Some`. If no path can be found, `None` is returned instead.
///
/// - `start` is the starting node.
/// - `successors` returns a list of successors for a given node, along with the
/// cost for moving from the node to the successor. This cost must be
/// non-negative.
/// - `success` checks whether the goal has been reached. It is not a node as
/// some problems require a dynamic solution instead of a fixed node.
///
/// A node will never be included twice in the path as determined by the `Eq`
/// relationship.
///
/// The returned path comprises both the start and end node.
///
/// # Example
///
/// We will search the shortest path on a chess board to go from (1, 1) to (4,
/// 6) doing only knight moves.
///
/// The first version uses an explicit type `Pos` on which the required traits
/// are derived.
///
/// ```
/// use pathfinding::prelude::dijkstra;
///
/// #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// struct Pos(i32, i32);
///
/// impl Pos {
/// fn successors(&self) -> Vec<(Pos, usize)> {
/// let &Pos(x, y) = self;
/// vec![
/// Pos(x + 1, y + 2),
/// Pos(x + 1, y - 2),
/// Pos(x - 1, y + 2),
/// Pos(x - 1, y - 2),
/// Pos(x + 2, y + 1),
/// Pos(x + 2, y - 1),
/// Pos(x - 2, y + 1),
/// Pos(x - 2, y - 1),
/// ]
/// .into_iter()
/// .map(|p| (p, 1))
/// .collect()
/// }
/// }
///
/// static GOAL: Pos = Pos(4, 6);
/// let result = dijkstra(&Pos(1, 1), |p| p.successors(), |p| *p == GOAL);
/// assert_eq!(result.expect("no path found").1, 4);
/// ```
///
/// The second version does not declare a `Pos` type, makes use of more
/// closures, and is thus shorter.
/// ```
/// use pathfinding::prelude::dijkstra;
///
/// static GOAL: (i32, i32) = (4, 6);
/// let result = dijkstra(
/// &(1, 1),
/// |&(x, y)| {
/// vec![
/// (x + 1, y + 2),
/// (x + 1, y - 2),
/// (x - 1, y + 2),
/// (x - 1, y - 2),
/// (x + 2, y + 1),
/// (x + 2, y - 1),
/// (x - 2, y + 1),
/// (x - 2, y - 1),
/// ]
/// .into_iter()
/// .map(|p| (p, 1))
/// },
/// |&p| p == GOAL,
/// );
/// assert_eq!(result.expect("no path found").1, 4);
/// ```
// pub fn dijkstra<N, C, E, FN, IN, FS, PV>(
// start: &N,
// mut successors: FN,
// path_value: &PV,
// mut success: FS,
// ) -> Option<(Vec<E>, C)>
// where
// N: Eq + Hash + Clone,
// E: Clone + Default,
// C: Zero + Ord + Copy,
// FN: FnMut(&N) -> IN,
// PV: FnMut(&N, &N) -> E,
// IN: IntoIterator<Item = (N, C)>,
// FS: FnMut(&N) -> bool,
// {
// dijkstra_internal(start, &mut successors, path_value, &mut success)
// }
pub(crate) fn dijkstra_internal<N, C, E, FN, FS, PV>(
start: &N,
second: Option<&N>,
successors: &FN,
path_value: &PV,
success: &FS,
max_iter: usize,
) -> Option<(Vec<E>, Vec<N>, C)>
where
N: Eq + Hash + Clone,
C: Zero + Ord + Copy,
E: Clone + Default,
FN: Fn(&N) -> Vec<(N, C)>,
PV: Fn(&N, &N) -> E,
FS: Fn(&N) -> bool,
{
let (parents, reached) = run_dijkstra(start, second, successors, path_value, success, max_iter);
reached.map(|target| {
(
reverse_path(&parents, |&(p, ..)| p, |_, (_, _, e)| e, target),
reverse_path(&parents, |&(p, ..)| p, |v, (..)| v, target),
parents.get_index(target).unwrap().1 .1,
)
})
}
type DijkstrasRes<N, C, E> = (FxIndexMap<N, (usize, C, E)>, Option<usize>);
fn run_dijkstra<N, C, E, FN, FS, PV>(
start: &N,
second: Option<&N>,
successors: &FN,
path_value: &PV,
stop: &FS,
max_iter: usize,
) -> DijkstrasRes<N, C, E>
where
N: Eq + Hash + Clone,
C: Zero + Ord + Copy,
E: Clone + Default,
FN: Fn(&N) -> Vec<(N, C)>,
PV: Fn(&N, &N) -> E,
FS: Fn(&N) -> bool,
{
let mut i = 0usize;
let mut checked_second = {
// we only check second if we know that the second node has edges that aren't
// the first node.
if let Some(s) = second {
let next = successors(s);
next.into_iter()
.filter(|(next_i, _)| next_i != start)
.count()
<= MAX_OTHER_PATHS
} else {
true
}
};
let mut visited = FastHashSet::default();
let mut to_see = BinaryHeap::new();
to_see.push(SmallestHolder { cost: Zero::zero(), index: 0, hops: 0 });
let mut parents: FxIndexMap<N, (usize, C, E)> = FxIndexMap::default();
parents.insert(start.clone(), (usize::MAX, Zero::zero(), E::default()));
let mut target_reached = None;
'outer: while let Some(SmallestHolder { cost, index, hops }) = to_see.pop() {
if hops >= MAX_LEN {
continue
}
if i == max_iter {
tracing::debug!("max iter on dijkstra hit");
break
}
let (node, _) = parents.get_index(index).unwrap();
if visited.contains(node) {
continue
}
if stop(node) {
target_reached = Some(index);
break
}
let successors = successors(node);
let base_node = node.clone();
for (successor, move_cost) in &successors {
let break_after = if !checked_second {
let second = second.unwrap();
checked_second = successor == second;
if !checked_second {
continue
}
true
} else {
false
};
i += 1;
if visited.contains(successor) {
continue
}
let new_cost = cost + *move_cost;
let value = path_value(&base_node, successor);
let q_break = stop(successor);
let n;
match parents.entry(successor.clone()) {
Vacant(e) => {
n = e.index();
e.insert((index, new_cost, value));
}
Occupied(mut e) => {
if e.get().1 > new_cost {
n = e.index();
e.insert((index, new_cost, value));
} else {
continue
}
}
}
// because our weight system is arbitrary,
// we don't want to prove we have the shortest path
if q_break {
target_reached = Some(n);
break 'outer
}
to_see.push(SmallestHolder { cost: new_cost, index: n, hops: hops + 1 });
if break_after {
break
}
}
if !checked_second {
checked_second = true;
for (successor, move_cost) in successors {
i += 1;
if visited.contains(&successor) {
continue
}
let new_cost = cost + move_cost;
let value = path_value(&base_node, &successor);
let q_break = stop(&successor);
let n;
match parents.entry(successor) {
Vacant(e) => {
n = e.index();
e.insert((index, new_cost, value));
}
Occupied(mut e) => {
if e.get().1 > new_cost {
n = e.index();
e.insert((index, new_cost, value));
} else {
continue
}
}
}
if q_break {
target_reached = Some(n);
break 'outer
}
to_see.push(SmallestHolder { cost: new_cost, index: n, hops: hops + 1 });
}
}
visited.insert(base_node);
}
(parents, target_reached)
}
/// Build a path leading to a target according to a parents map, which must
/// contain no loop. This function can be used after [`dijkstra_all`] or
/// [`dijkstra_partial`] to build a path from a starting point to a reachable
/// target.
///
/// - `target` is reachable target.
/// - `parents` is a map containing an optimal parent (and an associated cost
/// which is ignored here) for every reachable node.
///
/// This function returns a vector with a path from the farthest parent up to
/// `target`, including `target` itself.
///
/// # Panics
///
/// If the `parents` map contains a loop, this function will attempt to build
/// a path of infinite length and panic when memory is exhausted.
///
/// # Example
///
/// We will use a `parents` map to indicate that each integer from 2 to 100
/// parent is its integer half (2 -> 1, 3 -> 1, 4 -> 2, etc.)
///
/// ```
/// use pathfinding::prelude::build_path;
///
/// let parents = (2..=100).map(|n| (n, (n / 2, 1))).collect();
/// assert_eq!(vec![1, 2, 4, 9, 18], build_path(&18, &parents));
/// assert_eq!(vec![1], build_path(&1, &parents));
/// assert_eq!(vec![101], build_path(&101, &parents));
/// ```
#[allow(clippy::implicit_hasher)]
#[allow(dead_code)]
//TODO: Will prune if not used
pub fn build_path<N, C>(target: &N, parents: &FastHashMap<N, (N, C)>) -> Vec<N>
where
N: Eq + Hash + Clone,
{
let mut rev = vec![target.clone()];
let mut next = target.clone();
while let Some((parent, _)) = parents.get(&next) {
rev.push(parent.clone());
next = parent.clone();
}
rev.reverse();
rev
}
struct SmallestHolder<K> {
cost: K,
index: usize,
hops: usize,
}
impl<K: PartialEq> PartialEq for SmallestHolder<K> {
fn eq(&self, other: &Self) -> bool {
self.cost == other.cost
}
}
impl<K: PartialEq> Eq for SmallestHolder<K> {}
impl<K: Ord> PartialOrd for SmallestHolder<K> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<K: Ord> Ord for SmallestHolder<K> {
fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost)
}
}
#[allow(clippy::needless_collect)]
fn reverse_path<N, V, F, K, E>(
parents: &FxIndexMap<N, V>,
mut parent: F,
mut collect: K,
start: usize,
) -> Vec<E>
where
E: Clone,
N: Eq + Hash + Clone,
K: for<'a> FnMut(&'a N, &'a V) -> &'a E,
F: FnMut(&V) -> usize,
{
let mut i = start;
let path = std::iter::from_fn(|| {
parents.get_index(i).map(|(node, value)| {
i = parent(value);
collect(node, value)
})
})
.collect::<Vec<&E>>();
// Collecting the going through the vector is needed to revert the path because
// the unfold iterator is not double-ended due to its iterative nature.
path.into_iter().cloned().rev().collect()
}