Lesson 143 of 296
Dijkstra's shortest path
What you will learn
- Shortest paths in weighted graphs
- Why BFS is not enough
- Dijkstra's algorithm step by step
- Network Delay Time
- Limits of Dijkstra
On this page
The problem
In a weighted graph, each edge has a cost: distance, time, price. The shortest path is the one with the smallest total weight, not the fewest edges. BFS (Lesson 141) only counts edges, so it fails when weights differ.
A --1--> B --1--> C
A --------5-----> CBFS says A → C directly (1 edge). The cheapest path is A → B → C, total 2.
Dijkstra's algorithm
Works when all weights are zero or positive.
- Set the distance to the start as 0 and every other node as infinity.
- Put
(0, start)in a min-heap ordered by distance (Lesson 139). - Repeatedly pop the node with the smallest known distance. At that moment its distance is final: no other path can be shorter, because every other route would start from a node at least as far away and only add non-negative weights.
- For each neighbour, if going through this node gives a shorter distance, update it and push it into the heap.
- Skip entries popped from the heap that are out of date (a shorter distance was already found).
Network Delay Time
Problem (LeetCode 743): n network nodes (numbered 1 to n) and directed edges [from, to, time]. A signal starts at node k. How long until every node receives it? Return -1 if some node can never receive it.
The answer is the largest of the shortest distances from k.
function networkDelayTime(times: [number, number, number][], n: number, k: number): number {
const graph: [number, number][][] = Array.from({ length: n + 1 }, () => []);
for (const [from, to, weight] of times) graph[from]!.push([to, weight]);
const dist = new Array<number>(n + 1).fill(Infinity);
dist[k] = 0;
const heap = new Heap<[number, number]>((a, b) => a[0] - b[0]);
heap.push([0, k]);
while (heap.size > 0) {
const [d, node] = heap.pop()!;
if (d > dist[node]!) continue;
for (const [next, weight] of graph[node]!) {
const candidate = d + weight;
if (candidate < dist[next]!) {
dist[next] = candidate;
heap.push([candidate, next]);
}
}
}
let longest = 0;
for (let node = 1; node <= n; node++) {
if (dist[node] === Infinity) return -1;
longest = Math.max(longest, dist[node]!);
}
return longest;
}- The heap stores
[distance, node]pairs. if (d > dist[node]) continueskips stale entries. We push a node again whenever its distance improves instead of updating it inside the heap (simpler, and the standard approach in JavaScript).- Nodes are numbered from 1, so arrays have size n + 1.
O((V + E) log V) time with a binary heap, O(V + E) space.
Limits and related algorithms
| Situation | Use |
|---|---|
| Unweighted graph | BFS: simpler and O(V + E) |
| Non-negative weights | Dijkstra |
| Negative weights | Bellman-Ford, O(V × E). Dijkstra gives wrong answers with negative edges. |
| Shortest paths between all pairs, small graph | Floyd-Warshall, O(V³) |
| Road maps with a good distance estimate | A* (Dijkstra guided by an estimate of the remaining distance) |
| "Cheapest flight with at most k stops" | A modified Bellman-Ford or BFS by levels (LeetCode 787) |
Real-world uses: map routing, network routing protocols, game path finding.
How to say it in an interview
"For shortest paths with non-negative weights I use Dijkstra: distances start at infinity except the source, and a min-heap always gives the closest unfinalised node. When a node is popped its distance is final, so I relax its edges, pushing improved distances, and skip stale heap entries. It runs in O((V plus E) log V). For Network Delay Time the answer is the maximum of the shortest distances, or minus one if any node is unreachable. Unweighted graphs only need BFS, and negative weights need Bellman-Ford."
Key words
| Word | Meaning |
|---|---|
| Weighted graph | A graph whose edges have costs |
| Shortest path | The path with the smallest total weight |
| Dijkstra's algorithm | Shortest paths with non-negative weights using a min-heap |
| Relax an edge | Update a neighbour's distance if a shorter path is found |
| Stale entry | An old heap item whose distance has since improved |
| Bellman-Ford | A slower shortest-path algorithm that allows negative weights |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.