← 中文资源

简体中文版本

无权图 BFS 最短路径(JavaScript)

用广度优先搜索在无权图中找最短路径,用前驱映射重建路径。

阅读英文原文

实现说明

除了函数 bfsShortestPath,文件里再无其他定义。 迭代是嵌套的:while (queue.length) 框定这一趟,for (const neighbor of graph[node] || []) 做逐项处理。 返回新建的值,入参维持原状。

使用要点

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

常见问题

bfsShortestPath 会修改传入的参数吗?

入参保持不变;拿回来的是新建的值。

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 bfsShortestPath。

主要签名是 function bfsShortestPath(graph, start, end)

核心语句

if (start === end) return [start];
const visited = new Set([start]);
const parent = new Map();

代码示例

function bfsShortestPath(graph, start, end) {
  if (start === end) return [start];
  const queue = [start];
  const visited = new Set([start]);
  const parent = new Map();
  while (queue.length) {
    const node = queue.shift();
    for (const neighbor of graph[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;
}