Hey everyone, I’m wiring up a route finder for a small map tool, and my Dijkstra code mostly works until there are multiple entries for the same node in the heap. I skipped a decrease-key setup because life is short, but now it sometimes settles a worse distance first and the result is off.
function shortestPath(graph, start) {
const dist = {};
const seen = new Set();
const heap = [[0, start]];
for (const node in graph) dist[node] = Infinity;
dist[start] = 0;
while (heap.length) {
heap.sort((a, b) => a[0] - b[0]);
const [d, node] = heap.shift();
if (seen.has(node)) continue;
seen.add(node);
for (const [next, w] of graph[node]) {
const nd = d + w;
if (nd < dist[next]) {
dist[next] = nd;
heap.push([nd, next]);
}
}
}
return dist;
}
What is the clean fix here if I want to keep duplicate heap entries instead of adding a real decrease-key operation?
Arthur