Dijkstra Shortest Path With Min Heap (Rust)

Compute single source shortest paths in a weighted Rust graph using Dijkstra with BinaryHeap.

RustData Fetching

Code

rustsnippet
16 lines
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
}

How it works

Count the function dijkstra as the entire surface area of Dijkstra Shortest Path With Min Heap (Rust).

Iteration happens inside while let Some(Reverse((d, node))) = heap.pop() — everything outside it runs once.

Applying it

The primary signature is fn dijkstra(graph: &HashMap<&str, Vec<(&str, i32)

Import dijkstra from the file and call it — the rest of the code is implementation detail.

Statements that matter

let mut dist: HashMap<&str, i32> = graph.keys().map(|&n| (n, i32::MAX)).collect();
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))); }
}
}

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `dijkstra` at load time.