Dijkstra's shortest path
Find the cheapest path from one vertex to all others in a graph with non-negative edge weights, by always settling the closest unfinished vertex next.
Description
Dijkstra's algorithm finds the shortest paths from a start vertex when edges have costs: distances, travel times, latencies, prices. It keeps a tentative distance for every vertex, starting at 0 for the start and infinity for the rest.
At each step it takes the closest vertex not yet finished. Because all edge weights are non-negative, no later path can make that vertex cheaper, so its distance is now final. Then it relaxes each outgoing edge: if going through this vertex makes a neighbor cheaper, update the neighbor's distance and remember where it came from.
A priority queue (usually a binary heap) makes "take the closest" efficient. Recording each vertex's predecessor lets you rebuild the actual path, which together form a shortest-path tree, highlighted in the step-through.
Dijkstra's algorithm underpins route planning, network routing protocols such as OSPF, and many scheduling problems. It fails with negative edge weights; Bellman-Ford handles those. For a single destination on a map, A* adds a distance estimate to reach it faster.
How it works
Six cities and the travel times between them
- A — B (weight 4)
- A — C (weight 2)
- B — D (weight 5)
- C — D (weight 8)
- C — E (weight 10)
- D — F (weight 2)
- E — F (weight 3)
Step through: shortest travel times from A
Priority queue A (0)Visited in order none yet
Step 1 of 15Distance to A is 0; every other vertex starts at infinity.
Complexity
| Operation | Average | Worst |
|---|---|---|
| With a binary heap | O((V + E) log V) | O((V + E) log V) |
| With an unsorted arrayFine, even faster, for small dense graphs. | O(V²) | O(V²) |
| With a Fibonacci heapBetter in theory; rarely faster in practice. | O(E + V log V) | O(E + V log V) |
Space: O(V) for distances, predecessors and the queue
TypeScript implementation
Dijkstra's algorithm with a binary-heap priority queue, returning distances and the shortest route to a destination.
// Dijkstra's algorithm with a small binary-heap priority queue.
type Edge = { to: string; weight: number };
type Graph = Record<string, Edge[]>;
class MinQueue {
private heap: [number, string][] = [];
get size(): number {
return this.heap.length;
}
push(item: [number, string]): void {
const h = this.heap;
h.push(item);
for (let i = h.length - 1; i > 0; ) {
const p = (i - 1) >> 1;
if (h[p][0] <= h[i][0]) break;
[h[p], h[i]] = [h[i], h[p]];
i = p;
}
}
pop(): [number, string] {
const h = this.heap;
const top = h[0];
const last = h.pop()!;
if (h.length) {
h[0] = last;
for (let i = 0; ; ) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < h.length && h[l][0] < h[m][0]) m = l;
if (r < h.length && h[r][0] < h[m][0]) m = r;
if (m === i) break;
[h[m], h[i]] = [h[i], h[m]];
i = m;
}
}
return top;
}
}
export function dijkstra(g: Graph, start: string) {
const dist: Record<string, number> = { [start]: 0 };
const prev: Record<string, string> = {};
const queue = new MinQueue();
queue.push([0, start]);
while (queue.size) {
const [d, u] = queue.pop();
if (d > (dist[u] ?? Infinity)) continue; // a stale entry: we already found better
for (const { to, weight } of g[u] ?? []) {
const nd = d + weight;
if (nd < (dist[to] ?? Infinity)) {
dist[to] = nd;
prev[to] = u;
queue.push([nd, to]);
}
}
}
return { dist, prev };
}
export function route(prev: Record<string, string>, target: string): string[] {
const path = [target];
while (prev[path[0]]) path.unshift(prev[path[0]]);
return path;
}
export function demo(): string[] {
const roads: [string, string, number][] = [["A", "B", 4], ["A", "C", 2], ["B", "D", 5], ["C", "D", 8], ["C", "E", 10], ["D", "F", 2], ["E", "F", 3]];
const g: Graph = {};
for (const [a, b, w] of roads) {
(g[a] ??= []).push({ to: b, weight: w });
(g[b] ??= []).push({ to: a, weight: w }); // roads go both ways
}
const { dist, prev } = dijkstra(g, "A");
return [
`travel times from A: ${Object.entries(dist).sort().map(([v, d]) => `${v}=${d}`).join(", ")}`,
`fastest route A → F: ${route(prev, "F").join(" → ")} (${dist.F})`,
`fastest route A → E: ${route(prev, "E").join(" → ")} (${dist.E})`,
];
}When to use it
Use it when
- Shortest or cheapest paths with non-negative weights: routes, network latency, costs.
- You need distances from one source to many destinations.
- As a building block: many scheduling and resource problems reduce to shortest paths.
Avoid it when
- Some weights are negative: use Bellman-Ford.
- All weights are equal: BFS is simpler and faster.
- You need paths between all pairs on a small graph: Floyd-Warshall may be simpler.
- You're routing to one target on a map with coordinates: A* is usually much faster.
Pitfalls
- Negative edges, which silently produce wrong answers.
- Processing stale queue entries: with a simple binary heap you push duplicates; skip entries whose distance is larger than the current best.
- Stopping too early or too late: for a single destination you can stop when it's taken from the queue, not when it's first reached.
Alternatives
Breadth-first search
Choose it when every edge costs the same.
A* search
Choose it when you have one destination and a good estimate of the remaining distance.
Bellman-Ford
Choose it when edges can be negative, or you need to detect negative cycles.