-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdijkstra_priority_queue.rs
More file actions
75 lines (64 loc) · 2.1 KB
/
dijkstra_priority_queue.rs
File metadata and controls
75 lines (64 loc) · 2.1 KB
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
use std::{
cmp::Reverse,
collections::{BinaryHeap, HashMap, HashSet},
};
use crate::dijkstra::{Name, Price, Route};
pub fn shortest_path(
routes: &HashMap<Name, Route>,
start: Name,
destination: Name,
) -> Vec<Name> {
let mut prices: HashMap<Name, Price> = HashMap::new();
let mut stopovers: HashMap<Name, Name> = HashMap::new();
let mut visited: HashSet<Name> = HashSet::new();
let mut unvisited: BinaryHeap<Reverse<(Price, Name)>> = BinaryHeap::new();
prices.insert(start, 0);
unvisited.push(Reverse((0, start)));
while let Some(Reverse((price, current))) = unvisited.pop() {
if !visited.insert(current) {
continue;
}
if let Some(neighbors) = routes.get(¤t) {
for (&adjacent, &adj_price) in neighbors {
let new_price = price.saturating_add(adj_price);
if prices.get(&adjacent).is_none_or(|&p| new_price < p) {
prices.insert(adjacent, new_price);
stopovers.insert(adjacent, current);
unvisited.push(Reverse((new_price, adjacent)));
}
}
}
}
let mut path = Vec::new();
let mut current = destination;
while current != start {
path.push(current);
current = stopovers
.get(¤t)
.expect("stopovers must contain cities unless start is reached");
}
path.push(start);
path.reverse();
path
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dijkstra::sample;
#[test]
fn test_shortest_path() {
let s = sample::data();
let path = shortest_path(&s.routes, s.atlanta.name, s.elpaso.name);
assert_eq!(
path,
vec![s.atlanta.name, s.denver.name, s.chicago.name, s.elpaso.name]
);
}
#[test]
fn test_shortest_path_same_city() {
let s = sample::data();
let routes = HashMap::from([(s.atlanta.name, HashMap::from([]))]);
let path = shortest_path(&routes, s.atlanta.name, s.atlanta.name);
assert_eq!(path, vec![s.atlanta.name]);
}
}