function dijkstra(grid: Grid, start: Cell, goal: Cell) {const open = new MinHeap<Cell>([start]);
const distance = new Map([[start, 0]]), parent = new Map();
while (open.size > 0) {const current = open.pop(); // lowest distance
if (current === goal) return rebuild(parent, current);
for (const neighbor of neighbors(grid, current)) {const newDistance = distance.get(current)! + cost(grid, neighbor);
if (newDistance < (distance.get(neighbor) ?? Infinity)) {distance.set(neighbor, newDistance); parent.set(neighbor, current);
open.push(neighbor, newDistance);
}
}
}
}
Start at (3, 1), goal at (8, 42). The open set holds only the start.
Understanding Dijkstra
The idea
Dijkstra's algorithm is breadth-first search with a price tag. Instead of a queue it keeps a priority queue ordered by g, the cheapest known cost to reach each cell, and always expands the cheapest open cell. When a neighbour can be reached more cheaply through the current cell, its cost and parent are updated.
On this grid the amber cells are mud and cost 4 instead of 1. BFS would walk straight through them, counting steps; Dijkstra routes around them when the detour is cheaper, and the first time it pops the goal the path is the cheapest one, not merely the shortest.
The four stages
Complexity
Versus its siblings
Pseudocode
DIJKSTRA(start, goal)
open ← {start}; dist[start] ← 0while open not empty
current ← node in open with lowest dist
if current = goal: return path via parent
for each neighbour of current
if dist[current] + cost(neighbour) < dist[neighbour]
dist[neighbour] ← dist[current] + cost(neighbour); parent[neighbour] ← current; add neighbour to open
When to use
Pitfalls
History
Edsger Dijkstra designed the algorithm in 1956 in about twenty minutes, at a café in Amsterdam, as a demonstration for the ARMAC computer: the shortest route between two Dutch cities. He published it in 1959 in a three-page paper. With Fibonacci heaps, Fredman and Tarjan brought it to O(E + V log V) in 1984.