Overview
Dijkstra's algorithm finds the shortest path from one source to every other node in a graph with non-negative edge weights. It repeatedly takes the unvisited node with the smallest known distance, finalizes it, and relaxes its outgoing edges (tries to improve neighbors' distances through it).
A min-heap keyed by distance makes this O((V + E) log V). The greedy choice is safe because with non-negative weights, no later path can ever be shorter than the current smallest distance. With negative edges that guarantee breaks, and you need Bellman-Ford instead.
Pour water into the source. It reaches the nearest junction first, then spreads from there. The order in which junctions get wet is exactly the order Dijkstra finalizes them: by shortest travel time from the source.
When to use it
- Shortest path or minimum cost with non-negative weights.
- Network delay, travel time, cheapest route, minimum effort.
- Grid problems where moves have different costs.
- State-space search where each state has a cost (Dijkstra on (node, extra state)).
Problem patterns it solves
Recognize it when: time for a signal to reach all nodes.
- 743. Network Delay Time
- 1976. Number of Ways to Arrive at Destination
Recognize it when: minimize the largest step or effort along a path.
- 1631. Path With Minimum Effort
- 778. Swim in Rising Water
Recognize it when: multiply probabilities; use a max-heap.
- 1514. Path with Maximum Probability
Recognize it when: node plus stops used, fuel, or keys collected.
- 787. Cheapest Flights Within K Stops
- 1293. Shortest Path in a Grid with Obstacles Elimination
- 2093. Minimum Cost to Reach City With Discounts
Recognize it when: cells have costs or moves cost differently.
- 1368. Minimum Cost to Make at Least One Valid Path
- 2290. Minimum Obstacle Removal to Reach Corner
Where it is used in real software
Google Maps and Waze use Dijkstra-based algorithms (with A* heuristics and precomputed contraction hierarchies) over road networks with travel-time weights.
Link-state routing protocols such as OSPF and IS-IS run Dijkstra on each router to build forwarding tables.
Pathfinding for units across terrain with different movement costs uses Dijkstra or A*.
Delivery routing finds the cheapest or fastest route between warehouses and customers.
Key terms
- dist[v]
- Best known distance from the source to v.
- Relaxation
- If dist[u] + w < dist[v], update dist[v] and push it to the heap.
- Finalized
- When a node is popped with its current distance, that distance is optimal.
- Stale entry
- A heap entry whose distance is larger than dist[v]; skip it.
How it works, step by step
- 1Initialize
dist[source] = 0 and all others Infinity. Push [0, source] to a min-heap.
- 2Pop the smallest distance
Take [d, u] from the heap.
- 3Skip stale entries
If d > dist[u], a better path was already found; continue.
- 4Relax each edge u -> v with weight w
If d + w < dist[v], set dist[v] = d + w and push [dist[v], v].
- 5Repeat until the heap is empty
Or stop early when the target is popped.
Shortest distances from A
Edges: A-B 4, A-C 1, C-B 2, B-D 1, C-D 5
| Pop | Relaxations | dist A, B, C, D | Heap after |
|---|---|---|---|
| A (0) | B = 4, C = 1 | 0, 4, 1, inf | [C1, B4] |
| C (1) | B: 1 + 2 = 3 < 4, D: 1 + 5 = 6 | 0, 3, 1, 6 | [B3, B4, D6] |
| B (3) | D: 3 + 1 = 4 < 6 | 0, 3, 1, 4 | [B4, D4, D6] |
| B (4) | stale, skip | 0, 3, 1, 4 | [D4, D6] |
| D (4) | - | 0, 3, 1, 4 | [D6] |
| D (6) | stale, skip | 0, 3, 1, 4 | [] |
NOWPop: A (0) | Relaxations: B = 4, C = 1 | dist A, B, C, D: 0, 4, 1, inf | Heap after: [C1, B4]
The shortest path to D is A -> C -> B -> D with cost 4, even though the direct-looking edges suggested 5 or 6. Stale heap entries are how the simple version handles updated distances without a decrease-key operation.
Implementation
// Uses the PriorityQueue class from the Heap guidefunction dijkstra(n, edges, source) { const graph = Array.from({ length: n }, () => []); for (const [u, v, w] of edges) graph[u].push([v, w]); const dist = new Array(n).fill(Infinity); dist[source] = 0; const heap = new PriorityQueue((a, b) => a[0] - b[0]); heap.push([0, source]); while (heap.size) { const [d, u] = heap.pop(); if (d > dist[u]) continue; // stale entry for (const [v, w] of graph[u]) { if (d + w < dist[v]) { dist[v] = d + w; heap.push([dist[v], v]); } } } return dist;} // 743. Network Delay Time (1-indexed nodes)function networkDelayTime(times, n, k) { const dist = dijkstra(n + 1, times, k).slice(1); const worst = Math.max(...dist); return worst === Infinity ? -1 : worst;}Complexity and performance
Standard implementation.
Better for very dense graphs.
Graph, distances, heap.
Each cell is a node.
Trade-offs
If every edge has the same weight, BFS is simpler and O(V + E). With weights 0 and 1 only, 0-1 BFS with a deque is also O(V + E).
Dijkstra is much faster but fails with negative weights. Bellman-Ford handles negatives and detects negative cycles in O(V x E).
A* adds a heuristic estimate of the remaining distance to reach one target faster; with a zero heuristic it is Dijkstra.
Variants and related techniques
Store parent[v] = u when relaxing; walk back from the target.
When d + w === dist[v], add ways[u] to ways[v].
Push every source at distance 0 at the start.
Search from both ends and stop when they meet; used in road networks.
Common mistakes
- Using Dijkstra with negative edges.
Fix: Its greedy finalization becomes wrong; use Bellman-Ford or SPFA.
- Not skipping stale entries.
Fix: Check if (d > dist[u]) continue, or the algorithm does extra work and may give wrong counts.
- Marking visited when pushing.
Fix: A node's distance is only final when popped.
- Integer overflow when adding weights in Java.
Fix: Skip nodes with MAX_VALUE distance, or use long.
Interview questions
Why does Dijkstra fail with negative weights?
It finalizes a node when it is popped, assuming no later path can be cheaper. A negative edge discovered later could make an already-finalized distance smaller.
How would you solve Cheapest Flights Within K Stops?
Run Dijkstra (or Bellman-Ford for k + 1 rounds) on states (city, stops used), because the cheapest path might use too many stops and a pricier path with fewer stops can be the valid answer.
Practice problems
| Problem | Difficulty | What it trains |
|---|---|---|
| 743. Network Delay Time | Medium | Core template. |
| 1514. Path with Maximum Probability | Medium | Max-heap on products. |
| 1631. Path With Minimum Effort | Medium | Bottleneck distance. |
| 787. Cheapest Flights Within K Stops | Medium | Extra state. |
| 1976. Number of Ways to Arrive at Destination | Medium | Counting shortest paths. |
| 778. Swim in Rising Water | Hard | Minimize the maximum. |