Graph BFS Shortest Path Unweighted (Rust)

Find the shortest path in an unweighted Rust graph using BFS with a predecessor map for path reconstruction.

RustData Fetching

Code

rustsnippet
17 lines
use std::collections::{HashMap, VecDeque};

fn bfs_shortest_path(graph: &HashMap<&str, Vec<&str>>, start: &str, end: &str) -> Option<Vec<String>> {
    if start == end { return Some(vec![start.to_string()]); }
    let mut queue = VecDeque::new(); queue.push_back(start);
    let mut visited = HashMap::new(); visited.insert(start, true);
    let mut parent = HashMap::new();
    while let Some(node) = queue.pop_front() {
        for neighbor in graph.get(node).unwrap_or(&vec![]) {
            if *visited.get(neighbor).unwrap_or(&false) { continue; }
            visited.insert(neighbor, true); parent.insert(neighbor, node);
            if neighbor == &end { let mut path = vec![end.to_string()]; let mut cur = end; while let Some(&p) = parent.get(cur) { path.insert(0, p.to_string()); cur = p; } return Some(path); }
            queue.push_back(neighbor);
        }
    }
    None
}

How it works

Count the function bfs_shortest_path as the entire surface area of Graph BFS Shortest Path Unweighted (Rust).

Iteration happens inside while let Some(node) = queue.pop_front() — everything outside it runs once.

Applying it

The primary signature is fn bfs_shortest_path(graph: &HashMap<&str, Vec<&str>>, start: &str, end: &str) -> Option<Vec<String>>

bfs_shortest_path is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

if start == end { return Some(vec![start.to_string()]); }
if *visited.get(neighbor).unwrap_or(&false) { continue; }

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `std::collections`. The file defines `bfs_shortest_path` at load time.