Dijkstra's algorithm
Dijkstra’s algorithm finds shortest paths with non-negative weights. It settles the closest unsettled vertex and relaxes its edges using a priority queue.
Before you start: Shortest paths in unweighted graphs; path reconstruction, Priority queues in practice: top-k, k-way merge, scheduling.
The idea
A navigator finds the fastest routes by always extending the closest place it has not finished yet.
Dijkstra's algorithm formalizes this habit. It needs every road to take zero or more time.
Intuition
Start at 0 with distance 0. Its neighbors get tentative distances: 4 for node 1 and 1 for node 2.
Node 2 is closest, so settle it. Its edge to 1 gives 1 + 2 = 3, which beats the tentative 4.
Node 1 is now the closest unsettled node, so its distance 3 is final. Its edge to 3 gives 3 + 5 = 8.
Every unsettled node is at least as far as the closest one. Weights are not negative, so a detour cannot get shorter.
Complexity
Each edge can push one queue entry, and each push or pop costs O(log V). The total is O((V + E) log V).
With a plain array instead of a heap, every pop scans V entries and the total grows to O(V²).
Space is O(V + E). The table holds V distances, and the heap can hold one entry per relaxed edge.
Pitfalls
A negative edge breaks the rule. Node 1 is settled at 2, yet the route through node 2 costs only 1.
A queue can hold two entries for one node. Skip the older, larger entry when it is popped.
Most heaps cannot lower a key in place. Pushing a new entry and ignoring the stale one is simpler.
Variations
With one target, stop as soon as it is popped. Its distance is already final.
Code
Pseudocode
dist[all] ← ∞, dist[source] ← 0
pq ← [(0, source)]
while pq not empty
(d, u) ← pop smallest from pq
if d > dist[u]: continue
for each edge (u, v, w)
if d + w < dist[v]
dist[v] ← d + w
push (dist[v], v) onto pq
Python
import heapq
def dijkstra(adj, source):
dist = [float("inf")] * len(adj)
dist[source] = 0
pq = [(0, source)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(pq, (dist[v], v))
return dist
JavaScript
function dijkstra(adj, source) {
const dist = new Array(adj.length).fill(Infinity);
dist[source] = 0;
const pq = [[0, source]];
while (pq.length > 0) {
pq.sort((a, b) => a[0] - b[0]);
const [d, u] = pq.shift();
if (d > dist[u]) continue;
for (const [v, w] of adj[u]) {
if (d + w < dist[v]) {
dist[v] = d + w;
pq.push([dist[v], v]);
}
}
}
return dist;
}
Cost at a glance
| Time | O((V + E) log V) |
|---|---|
| Space | O(V) |
| Input | Non-negative edge weights |
| Output | Shortest distances from a source |
Practice problems (6)
Relaxation table Warm-up
Follow Dijkstra from node 0. After each node is settled, type the distance that the next relaxation writes into the distance table.
Why no negative edges Warm-up
Dijkstra runs from node 0 on this directed graph, which has one negative edge. It settles node 1 at distance 2. Why is that answer unsafe?
Which node is settled next? Standard
Follow Dijkstra from node 0. Each time the queue is about to be popped, click the node that gets settled next.
Implement Dijkstra Standard
Return an array dist where dist[v] is the length of the shortest path from source to v, or -1 when v is unreachable. Weights are non-negative. buildAdjacency(graph) lists [neighbor, weight] pairs.
In Python, build the adjacency lists from graph["edges"] yourself.
Network delay time Standard
A signal starts at node k and travels along directed links. Each entry [u, v, w] in times is a link from u to v that takes w time units. Nodes are numbered 1 to n. Return the time until every node has the signal, or -1 when some node never gets it.
Path with minimum effort Challenge
You walk from the top-left to the bottom-right cell of a grid of heights, moving up, down, left or right. The effort of a route is the largest height difference between two neighboring cells on it. Return the smallest effort over all routes.
Related topics
Next on the path: Bellman-Ford and negative edges