题目
给定一个以邻接对象表示的带权有向图、起点与终点,求从起点到终点的最小路径总权重。节点名称是字符串,边权非负。如果终点不可达则返回 -1,起点与终点相同时代价为 0。输入约定为邻接表对象与两个节点名,输出约定为一个数值。
解题思路
Dijkstra 每次从尚未确定的节点中取出当前距离最小者进行扩展。用小顶堆按距离维护候选节点,取出堆顶即得到当前最优。对每个邻居尝试松弛:如果经过当前节点能得到更小的距离,就更新距离表并把新距离压入堆。已经过期的堆条目在弹出时通过比较距离直接跳过。
时间复杂度为 O((V+E) log V),空间复杂度为 O(V+E)。由于所有边权非负,节点一旦以最小距离弹出,其距离就不会再被改进,因此可以提前返回目标点。
参考实现要点
堆用手写数组实现上浮与下沉,压入和弹出都保持 O(log n)。距离表使用 Map,未访问节点默认视为无穷大。弹出条目后先与记录的距离比较,若更大则说明是旧条目,直接跳过。邻接对象中不存在的节点用空对象兜底。起点距离初始化为 0 后入堆。
常见错误
用 visited 集合在松弛前就标记节点,可能错过后来发现的更短路径。忘记跳过过期堆条目会重复处理节点,虽不影响正确性但会拖慢速度。把边权当成无向处理会改变答案。另一点是终点不可达时忘记返回 -1,可能误返回无穷大。
验证方式
三个样例分别覆盖绕行更便宜、唯一链条、不可达三种情况。再测试起点等于终点、直接边与多跳路径的取舍,以及只有单个节点的图。可用 Bellman-Ford 在小规模随机图上交叉验证最短距离,确保堆实现没有遗漏松弛。
代码示例
function dijkstra(graph, start, target) {
const distances = new Map([[start, 0]]);
const heap = [[0, start]];
const push = (entry) => {
heap.push(entry);
let index = heap.length - 1;
while (index > 0) {
const parent = (index - 1) >> 1;
if (heap[parent][0] <= heap[index][0]) break;
[heap[parent], heap[index]] = [heap[index], heap[parent]];
index = parent;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let index = 0;
for (;;) {
const left = index * 2 + 1;
const right = left + 1;
let smallest = index;
if (left < heap.length && heap[left][0] < heap[smallest][0]) smallest = left;
if (right < heap.length && heap[right][0] < heap[smallest][0]) smallest = right;
if (smallest === index) break;
[heap[index], heap[smallest]] = [heap[smallest], heap[index]];
index = smallest;
}
}
return top;
};
while (heap.length > 0) {
const [distance, node] = pop();
if (distance > (distances.get(node) ?? Infinity)) continue;
if (node === target) return distance;
for (const [neighbour, weight] of Object.entries(graph[node] ?? {})) {
const candidate = distance + weight;
if (candidate < (distances.get(neighbour) ?? Infinity)) {
distances.set(neighbour, candidate);
push([candidate, neighbour]);
}
}
}
return -1;
}