Dijkstra's Shortest Path — Algorithms

Dijkstra finds the shortest distance from one town (node) to every other town in a weighted graph: every road (edge) has a number, its weight, like its length…

You take a motorbike taxi from home to school. The straight road is 4 km, but the driver turns: 2 km to a junction, then 1 km to school. That's 3 km in all. Two roads, yet shorter than the straight one.

Finding the shortest route, like the taxi's route, is the job of Dijkstra's algorithm. Dijkstra finds the shortest distance from one node to every other node in a weighted graph. In this lesson, the nodes are towns and the edges are the roads between towns. A weight is the number on each road, like its length in km. BFS only counts how many roads you take, while Dijkstra adds up their lengths. This is like a map app finding the shortest route from your home. There's one condition: no weight may be negative.

Take the nearest, then check its roads

There are five towns, A to E, with two-way roads: A-B 4 km, A-C 2, B-C 1, B-D 5, C-D 8, C-E 10 and D-E 2. Dijkstra keeps dist, the shortest distance from A to each town found so far. A town whose distance is final (surely the shortest, and it won't change again) is called finished. Dijkstra repeats these two steps:

  1. Take the unfinished town with the smallest dist. Its distance is now final, and the town is finished.
  2. Check every road from that town to its neighbours. If the distance through that town is shorter than the neighbour's distance on record (or the neighbour has no record yet), replace the record. This step is called relaxation.

Here's how it runs, starting from A. In the last column, steps 2 to 4 only show the distances that changed:

Step Take (final) What changes dist afterwards
1 A (0) B: 0 + 4 = 4, C: 0 + 2 = 2 A 0, B 4, C 2
2 C (2) B: 2 + 1 = 3, shorter than 4. D: 2 + 8 = 10. E: 2 + 10 = 12 B 3, D 10, E 12
3 B (3) D: 3 + 5 = 8, shorter than 10 D 8
4 D (8) E: 8 + 2 = 10, shorter than 12 E 10
5 E (10) (nothing) done

B's distance drops from 4 to 3: the detour through C is shorter, just like the taxi ride at the start of this lesson.

Here is the code for the same five towns. Each town keeps a list of [neighbour, weight] pairs:

const graph = {
  A: [["B", 4], ["C", 2]],
  B: [["A", 4], ["C", 1], ["D", 5]],
  C: [["A", 2], ["B", 1], ["D", 8], ["E", 10]],
  D: [["B", 5], ["C", 8], ["E", 2]],
  E: [["C", 10], ["D", 2]],
};

function dijkstra(graph, start) {
  const dist = {};
  dist[start] = 0;
  const done = new Set();

  while (true) {
    let u = null; // the unfinished town with the smallest distance
    for (const node in dist) {
      if (!done.has(node) && (u === null || dist[node] < dist[u])) u = node;
    }
    if (u === null) break; // every reachable town is finished
    done.add(u); // the distance of u is final now

    for (const [v, w] of graph[u]) {
      const newDist = dist[u] + w;
      if (dist[v] === undefined || newDist < dist[v]) dist[v] = newDist; // relaxation
    }
  }
  return dist;
}

console.log(dijkstra(graph, "A")); // { A: 0, B: 3, C: 2, D: 8, E: 10 }

The dijkstra function gives only the distances, not the route. A map app needs the route too: which towns to pass. To get it, each time relaxation changes dist[v], also record prev[v] = u: the town before v on the best route so far. When every town is finished, read the route backwards from the destination: prev[E] = D, prev[D] = B, prev[B] = C, and prev[C] = A. This code uses the graph above:

function dijkstraRoute(graph, start, end) {
  const dist = {};
  dist[start] = 0;
  const prev = {}; // prev[v] = the town before v on the best route
  const done = new Set();
  while (true) {
    let u = null;
    for (const node in dist) {
      if (!done.has(node) && (u === null || dist[node] < dist[u])) u = node;
    }
    if (u === null) break;
    done.add(u);
    for (const [v, w] of graph[u]) {
      const newDist = dist[u] + w;
      if (dist[v] === undefined || newDist < dist[v]) {
        dist[v] = newDist;
        prev[v] = u; // the best road to v comes from u
      }
    }
  }
  if (dist[end] === undefined) return null; // the destination cannot be reached
  const path = [end];
  while (path[0] !== start) path.unshift(prev[path[0]]);
  return path;
}
console.log(dijkstraRoute(graph, "A", "E")); // ["A", "C", "B", "D", "E"]

path starts with the destination, E. The last loop takes the prev of the town at the front, and path.unshift puts it at the front of the array. The loop stops at start, so the result starts at A. The route A-C-B-D-E is 10 km long, the same as the dist of E in the table.

Why negative weights aren't allowed

Dijkstra assumes the distance of the town it takes is final, because that town has the smallest distance among the unfinished towns. That's true because any other route to that town must go through an unfinished town whose distance is already the same or bigger. Weights that aren't negative only add length, so the other route can't be shorter. With a negative weight, a shorter detour can be found later, after the town was already treated as final. So the result can be wrong. For graphs with negative weights, use the Bellman-Ford algorithm.

Speed and other choices

The code above checks every town each time it looks for the nearest one. For V towns that's about V × V steps, O(V²). That's fine for a small graph. For a big graph, take the nearest town from a min-heap (a priority queue): a data structure that gives you its smallest item quickly. Then it's O((V + E) log V), where E is the number of roads. log V is small: about 10 for 1,000 towns.

Pick the algorithm by the weights:

⚠️ Distances settled too soon, and BFS in the wrong place

TL;DR: Dijkstra finds the shortest distance from one town (node) to every other town in a weighted graph: every road (edge) has a number, its weight, like its length in km. No weight may be negative. Repeat two steps: among the towns whose distance isn't final yet, take the one with the smallest recorded distance (dist), and its distance becomes final. Then relax each of its roads: if dist[u] + w (that town's distance plus the road's weight) is smaller than dist[v], the neighbour's recorded distance (or dist[v] doesn't exist yet), replace it. A detour can be shorter than a direct road. Negative weights break the assumption that a town's distance, once the town is taken, is final, so use the Bellman-Ford algorithm. If it checks every town each time, Dijkstra is O(V²), where V is the number of towns. With a min-heap it's O((V + E) log V), where E is the number of roads.

⚡ Take the nearest, then relax

Write:

function dijkstra(graph, start) {
  const dist = {};
  dist[start] = 0;
  const done = new Set();

  while (true) {
    let u = null; // the unfinished town with the smallest distance
    for (const node in dist) {
      if (!done.has(node) && (u === null || dist[node] < dist[u])) u = node;
    }
    if (u === null) break; // every reachable town is finished
    done.add(u); // the distance of u is final now

    for (const [v, w] of graph[u]) {
      const newDist = dist[u] + w;
      if (dist[v] === undefined || newDist < dist[v]) dist[v] = newDist; // relaxation
    }
  }
  return dist;
}

Meaning: Dijkstra finds the shortest distance from the town start to every other town. Towns are nodes and roads are edges. graph[u] holds [neighbour, weight] pairs, and the weight is the road's length. dist records the shortest distance found so far, and done holds the finished towns (their distance is final). At each step, take the unfinished town u with the smallest dist: its distance is now final. Then check each road from u to a neighbour v with weight w. If dist[u] + w is smaller than the distance on record for v, or v has no distance yet, replace it. This step is called relaxation.

⚡ A detour can be shorter

Guess first: roads A-B 4 km, A-C 2 km, B-C 1 km. What's the shortest distance from A to B?

3 km, through C (2 + 1). So the first distance written down for B, 4, wasn't final.

Meaning: A distance is only final once its town is taken as the smallest. BFS picks the route with the fewest roads, Dijkstra the route with the smallest total weight.

⚡ Why negative weights aren't allowed

Meaning: Dijkstra assumes the distance of the town it takes (the smallest among the unfinished towns) is final. That's true because any other route must go through an unfinished town whose distance is already the same or bigger, and weights that aren't negative only add length. With a negative weight, a shorter detour can be found later, so the result can be wrong. For a graph with negative weights, use the Bellman-Ford algorithm.

What you will learn