← 中文资源

简体中文版本

Dijkstra 最短路径最小堆

用最小堆实现 Dijkstra 算法计算加权图单源最短路径。

阅读英文原文

实现说明

除了函数 dijkstra,文件里再无其他定义。 这里叠了两层循环:for (const n of graph.keys()) dist.set(n, Infinity); 负责挑选,while (heap.length) 负责处理。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 dijkstra。

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

核心语句

heap.sort((a, b) => a[0] - b[0]);
for (const [neighbor, weight] of graph.get(node) ?? []) {
  const nd = d + weight;
  if (nd < dist.get(neighbor)!) { dist.set(neighbor, nd); heap.push([nd, neighbor]); }
}
const dist = new Map<string, number>();

代码示例

function dijkstra(graph: Map<string, [string, number][]>, start: string): Map<string, number> {
  const dist = new Map<string, number>();
  const heap: [number, string][] = [[0, start]];
  for (const n of graph.keys()) dist.set(n, Infinity);
  dist.set(start, 0);
  while (heap.length) {
    heap.sort((a, b) => a[0] - b[0]);
    const [d, node] = heap.shift()!;
    if (d > dist.get(node)!) continue;
    for (const [neighbor, weight] of graph.get(node) ?? []) {
      const nd = d + weight;
      if (nd < dist.get(neighbor)!) { dist.set(neighbor, nd); heap.push([nd, neighbor]); }
    }
  }
  return dist;
}