Data Structures & Algorithms / Module 8: Graphs
Topic 8.4
Shortest path (Dijkstra)
The shortest route by road length: always process the nearest first.
Watch: the numbers on the roads are their lengths. The route with the fewest roads turns out not to be the shortest.
- moving now
- being checked
- passed / marked
- finished / the result
Fewer roads isn't always closer
Choose "fewest roads" in the figure. BFS picks A - B - D - F: only 3 roads, but 11 long. Dijkstra finds A - C - B - D - E - F: 5 roads, 7 long. As in real life, a longer highway often beats a congested shortcut.
Why the nearest one is settled
At every step, Dijkstra takes the place with the smallest tentative distance from the queue. That distance is treated as final right away. Why is that allowed? Any other route to that place must go through one of the other places in the queue, all of which are at least as far. With no negative road lengths, a detour through them can only add distance.
That's why Dijkstra is a greedy algorithm (Module 5) that is proven correct, and why it needs a heap (Module 7): to take the nearest one quickly.
Code, for programmersDijkstra with a min-heap
// graph: Map node -> array of [neighbour, length]
// MinHeap of [distance, node] pairs, compared by distance
function dijkstra(graph, start) {
const dist = new Map([[start, 0]]);
const from = new Map();
const heap = new MinHeap();
heap.push([0, start]);
while (heap.size) {
const [d, v] = heap.pop();
if (d > dist.get(v)) continue; // an old, outdated entry: skip it
for (const [u, len] of graph.get(v) ?? []) {
const nd = d + len;
if (nd < (dist.get(u) ?? Infinity)) { // a shorter way to u, through v
dist.set(u, nd);
from.set(u, v);
heap.push([nd, u]);
}
}
}
return { dist, from };
}Quiz
At each step, which place does Dijkstra process?
Why does Dijkstra use a heap?
When can Dijkstra give a wrong answer?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.