← 中文资源

简体中文版本

无权图 BFS 最短路径

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

阅读英文原文

实现说明

函数 bfsShortestPath承担主要逻辑,其余部分只做调用安排。 核心工作在嵌套循环里完成:外层 while (queue.length),内层 for (const neighbor of graph.get(node) ?? [])。 返回值是全新构造的——入参不会被交回去。

使用要点

  • 守卫 start === end 成立时借助提前的 return 直接离开。

常见问题

bfsShortestPath 会修改传入的参数吗?

没有原地修改——函数读取输入并返回新值。

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 bfsShortestPath。

主要签名是 function bfsShortestPath(graph: Map<string, string[]>, start: string, end: string)

核心语句

for (const neighbor of graph.get(node) ?? []) {
  if (visited.has(neighbor)) continue;
  visited.add(neighbor); parent.set(neighbor, node);
  if (neighbor === end) { const path = [end]; let cur = end; while (parent.has(cur)) { cur = parent.get(cur)!; path.unshift(cur); } return path; }
  queue.push(neighbor);
}
const parent = new Map<string, string>();
if (start === end) return [start];

代码示例

function bfsShortestPath(graph: Map<string, string[]>, start: string, end: string): string[] | null {
  if (start === end) return [start];
  const queue: string[] = [start];
  const visited = new Set([start]);
  const parent = new Map<string, string>();
  while (queue.length) {
    const node = queue.shift()!;
    for (const neighbor of graph.get(node) ?? []) {
      if (visited.has(neighbor)) continue;
      visited.add(neighbor); parent.set(neighbor, node);
      if (neighbor === end) { const path = [end]; let cur = end; while (parent.has(cur)) { cur = parent.get(cur)!; path.unshift(cur); } return path; }
      queue.push(neighbor);
    }
  }
  return null;
}