Shortest paths with a heap
Dijkstra’s algorithm finds the cheapest route from one place to all others.
collections.Heap always hands out the smallest item, so it gives the next
closest place. Implementing Order on a small struct tells the heap what
“smallest” means.
import collections
struct Step { cost: i64 node: i64}
impl Order for Step { fn compare(&self, other: &Step) -> i64 { return self.cost.compare(&other.cost) }}
let names = ["home", "bakery", "park", "office", "station"]let roads = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 5), (2, 3, 8), (3, 4, 3)]
let mut next: Vec<Vec<(i64, i64)>> = []for _ in 0..names.len() { next.push([])}for (a, b, cost) in roads { next[a].push((b, cost)) next[b].push((a, cost))}
let far = 1000000let mut best: Vec<i64> = []for _ in 0..names.len() { best.push(far)}best[0] = 0let mut queue: collections.Heap<Step> = collections.Heap.new()queue.push(Step { cost: 0, node: 0 })while true { let step = match queue.pop() { Some(s) => s None => break } if step.cost > best[step.node] { continue } for (to, cost) in &next[step.node] { let through = step.cost + *cost if through < best[*to] { best[*to] = through queue.push(Step { cost: through, node: *to }) } }}for i in 0..names.len() { print(f"{names[i]:<8} {best[i]}")}home 0bakery 3park 1office 8station 11A step that comes out of the heap with a cost higher than the best already known is old news (a cheaper route was found after it was queued), so it is skipped instead of removed from the heap.