use std::collections::{VecDeque, HashMap, HashSet};
fn shortest_path(graph: &HashMap<i32, Vec<i32>>, start: i32, end: i32) -> Option<Vec<i32>> {
let mut queue = VecDeque::new();
let mut visited = HashSet::new();
let mut parent = HashMap::new();
queue.push_back(start);
visited.insert(start);
while let Some(node) = queue.pop_front() {
if node == end {
let mut path = Vec::new();
let mut current = end;
while current != start {
path.push(current);
current = *parent.get(¤t).unwrap();
}
path.push(start);
path.reverse();
return Some(path);
}
if let Some(neighbors) = graph.get(&node) {
for &neighbor in neighbors {
if !visited.contains(&neighbor) {
visited.insert(neighbor);
parent.insert(neighbor, node);
queue.push_back(neighbor);
}
}
}
}
None
}
fn main() {
let mut graph = HashMap::new();
graph.insert(1, vec![2, 4]);
graph.insert(2, vec![3]);
graph.insert(3, vec![]);
graph.insert(4, vec![2]);
if let Some(path) = shortest_path(&graph, 1, 3) {
let path_str = path.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(" -> ");
println!("{}", path_str);
println!("Shortest path found: {}", path_str);
} else {
println!("No path found");
}
}
queue.push_back(start);
visited.insert(start);
Initialize queue and visited set with start node
while let Some(node) = queue.pop_front() {
Process nodes in breadth-first order to find shortest path
if node == end { ... return Some(path); }
Stop when destination is reached and reconstruct path
for &neighbor in neighbors { if !visited.contains(&neighbor) { ... } }
Add unvisited neighbors to queue and track their parent
1 -> 2 -> 3
Shortest path found: 1 -> 2 -> 3