Dijkstra's
Algorithm
Find the shortest path from a source to every reachable vertex in a weighted graph. A min-heap priority queue and the relaxation step make it O((V+E) log V) — powering Google Maps, routers, and game pathfinding.
How does Dijkstra's algorithm work?
Dijkstra's algorithm finds the shortest path from a start node to every other node in a graph with non-negative edge weights. It repeatedly picks the unvisited node with the smallest known distance (using a priority queue), then relaxes its edges, updating a neighbour if going through this node is shorter. With a binary heap it runs in O((V + E) log V).
function dijkstra(graph, start) { // graph: { A: [["B", 4], ["C", 1]], … }
const dist = { [start]: 0 }, visited = new Set();
const pq = [[0, start]]; // use a real heap for big graphs
while (pq.length) {
pq.sort((a, b) => a[0] - b[0]);
const [d, node] = pq.shift();
if (visited.has(node)) continue;
visited.add(node);
for (const [next, w] of graph[node] ?? []) {
if (d + w < (dist[next] ?? Infinity)) { dist[next] = d + w; pq.push([d + w, next]); }
}
}
return dist;
}Shortest distances — animated
// Array state
// Pseudocode
Algorithm walkthrough
Initialise distances
Set dist[source] = 0 and dist[all others] = infinity. Push (0, source) into a min-heap priority queue. This represents 'I can reach source for free.'
Pseudocode
1function dijkstra(graph, source):2 dist = {v: infinity for each v}3 dist[source] = 04 pq = MinHeap() // (distance, vertex)5 pq.push((0, source))6 visited = Set()7 while pq not empty:8 (d, u) = pq.pop() // smallest dist first9 if u in visited: continue10 visited.add(u)11 for each (v, w) in graph[u].neighbors:12 if dist[u] + w < dist[v]:13 dist[v] = dist[u] + w // relax edge14 pq.push((dist[v], v))15 return dist
Complexity
Linearithmic time
Linear time
Constant time
🎯 Quick Check
Dijkstra processes node U and sees edge U→V with weight 3. dist[U]=5, dist[V]=9. Should it relax?
Dijkstra's Algorithm: summary
Key points
- It doesn't work with negative edge weights; use Bellman–Ford for those.
- Store each node's predecessor to reconstruct the actual path.
- A* adds a heuristic (such as straight-line distance) to search towards the goal faster.
Frequently asked questions
›Why doesn't Dijkstra work with negative weights?
It assumes that once a node has the smallest distance, no later path can be shorter. A negative edge discovered later can break that assumption.