Dijkstra Shortest Path With Min Heap (Rust)
Compute single source shortest paths in a weighted Rust graph using Dijkstra with BinaryHeap.
Code
use std::collections::{HashMap, BinaryHeap};
use std::cmp::Reverse;
fn dijkstra(graph: &HashMap<&str, Vec<(&str, i32)>>, start: &str) -> HashMap<&str, i32> {
let mut dist: HashMap<&str, i32> = graph.keys().map(|&n| (n, i32::MAX)).collect();
dist.insert(start, 0);
let mut heap = BinaryHeap::new(); heap.push(Reverse((0, start)));
while let Some(Reverse((d, node))) = heap.pop() {
if d > *dist.get(node).unwrap_or(&i32::MAX) { continue; }
for &(neighbor, weight) in graph.get(node).unwrap_or(&vec![]) {
let nd = d + weight;
if nd < *dist.get(neighbor).unwrap_or(&i32::MAX) { dist.insert(neighbor, nd); heap.push(Reverse((nd, neighbor))); }
}
}
dist
}Report a problem with this exampleOpens a pre-filled issue on GitHub.