← 中文资源

简体中文版本

无权图 BFS 最短路径(Rust)

用广度优先搜索在无权图中找最短路径并重建路径。

阅读英文原文

实现说明

全部逻辑都在函数 bfs_shortest_path中。 while let Some(node) = queue.pop_front() 反复执行,循环体之外没有别的重复。

使用要点

  • 把 bfs_shortest_path 当作 API:导入它,其余代码可以忽略。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 全部导入都来自标准库:std::collections。 文件在加载时定义 bfs_shortest_path。

主签名形如 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()]); }
if *visited.get(neighbor).unwrap_or(&false) { continue; }

代码示例

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
}