Graph BFS Shortest Path Unweighted (Rust)
Find the shortest path in an unweighted Rust graph using BFS with a predecessor map for path reconstruction.
Code
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
}Report a problem with this exampleOpens a pre-filled issue on GitHub.