实现说明
除了函数 dijkstra,文件里再无其他定义。
核心工作在嵌套循环里完成:外层 for (const n of Object.keys(graph)) dist.set(n, Infinity);,内层 while (heap.length)。
常见问题
除了语言工具链还要下载什么吗?
除了这个语言的工具链,什么都不用再下载。 文件在加载时定义 dijkstra。
签名一览:function dijkstra(graph, start)
核心语句
heap.sort((a, b) => a[0] - b[0]);
const dist = new Map();
代码示例
function dijkstra(graph, start) {
const dist = new Map();
const heap = [[0, start]];
for (const n of Object.keys(graph)) 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[node] || []) {
const nd = d + weight;
if (nd < dist.get(neighbor)) {
dist.set(neighbor, nd);
heap.push([nd, neighbor]);
}
}
}
return dist;
}