Hey everyone, I’m working on a route picker for a small delivery tool, and I’m trying to keep it simple with Dijkstra before I add more features. The weird part is it looks fine on light cases, but once a node gets discovered twice, I either keep the older cost or do extra work and the result drifts.
function shortestPath(graph, start) {
const dist = {};
const seen = new Set();
const pq = [[0, start]];
for (const node in graph) dist[node] = Infinity;
dist[start] = 0;
while (pq.length) {
pq.sort((a, b) => a[0] - b[0]);
const [cost, node] = pq.shift();
if (seen.has(node)) continue;
seen.add(node);
for (const [next, weight] of graph[node]) {
const nextCost = cost + weight;
if (nextCost < dist[next]) {
dist[next] = nextCost;
pq.push([dist[next], next]);
}
}
}
return dist;
}
What am I missing about when a node is safe to mark seen here if I want to avoid wasted queue entries without locking in the wrong distance?
Hari