Graph: Shortest Path — Data Structures

In a weighted graph, every edge has a number (its weight), and the length of a path is the sum of its weights. Dijkstra finds the shortest distances from one…

From A to B there's a straight main road, 4 km long. The maps app tells you to turn to C first: A to C is 2 km, then C to B is 1 km. It looks like a detour, but the total is only 3 km.

Drawn as a graph, A, B and C are nodes, and the roads are edges. In a weighted graph, every edge has a number (its weight), such as a distance in kilometres or minutes of travel. The length of a path is the sum of its edges' weights. The route A, C, B is called the shortest path: the cheapest route (the smallest total weight) from one node to another.

Dijkstra: continue from the cheapest node

Dijkstra's algorithm finds the shortest distance from one starting node to every other node. A node's distance here is the total weight of the best path found so far from the start to that node. It works like this:

  1. The start's distance is 0, every other node's is ∞ (Infinity, meaning no path has been found yet).
  2. Take the node that isn't final yet with the smallest distance, the cheapest node. Its distance is now final: Dijkstra treats it as the shortest and never takes that node again.
  3. Check every edge leaving that node. If the node's distance plus the edge's weight is smaller than the neighbour's recorded distance, replace the neighbour's distance. This step is called relaxation.
  4. Repeat steps 2 and 3 until no nodes are left.

The example is the same directed graph as in the Lab. Its edges: A to B (weight 4), A to C (2), C to B (1), C to E (5), B to D (3), and D to E (1). Here's how it runs, starting from A:

Take Edges checked Distances A, B, C, D, E after
A (0) A to B: 0 + 4, A to C: 0 + 2 0, 4, 2, ∞, ∞
C (2) C to B: 2 + 1 = 3, smaller than 4. C to E: 2 + 5 0, 3, 2, ∞, 7
B (3) B to D: 3 + 3 0, 3, 2, 6, 7
D (6) D to E: 6 + 1 = 7, not smaller than 7 0, 3, 2, 6, 7
E (7) no edges leave E done

The distance to B drops from 4 to 3: the detour through C from the start of this lesson really is shorter.

This is the Dijkstra code for the same graph:

const graph = {
  A: { B: 4, C: 2 },
  B: { D: 3 },
  C: { B: 1, E: 5 },
  D: { E: 1 },
  E: {},
};

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

  while (true) {
    // take the cheapest node that isn't final yet
    let node = null;
    for (const n in dist) {
      if (!done.has(n) && dist[n] < Infinity && (node === null || dist[n] < dist[node])) {
        node = n;
      }
    }
    if (node === null) break;
    done.add(node);

    // relaxation: check every neighbour
    for (const [next, w] of Object.entries(graph[node])) {
      if (dist[node] + w < dist[next]) {
        dist[next] = dist[node] + w;
      }
    }
  }
  return dist;
}

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

The Dijkstra code above gives only the distances, but a map app also shows the route. For the route, record for each node the node before it on its best path. Add const prev = {}; below const dist = {};. Then write prev[next] = node; inside the relaxation if, right after dist[next] changes. For this graph, prev ends up as { B: "C", C: "A", D: "B", E: "C" }. Read the route backwards from the destination. For D: D came from B, B from C, and C from A. This function, route, builds the route from prev:

function route(prev, start, end) {
  if (end !== start && !(end in prev)) return null; // cannot be reached
  const path = [end];
  while (path[0] !== start) path.unshift(prev[path[0]]);
  return path;
}
const prev = { B: "C", C: "A", D: "B", E: "C" };
console.log(route(prev, "A", "D")); // ["A", "C", "B", "D"]

The while loop walks back through prev until it reaches the start node, and path.unshift puts each node at the front of the array. So the route starts at A. A destination that cannot be reached has no key in prev (end in prev checks this), so route returns null.

Negative weights make Dijkstra wrong

Dijkstra assumes the distance of a node that's final can never go down again. That holds as long as every weight is 0 or more. With a negative weight, a cheaper path to a node can be found after that node is already final, and the nodes after it are never checked again.

Example: A to B 2, A to C 5, C to B -4, B to D 1. B (distance 2) is taken before C (distance 5), so D gets 2 + 1 = 3. When C is taken, the path A, C, B turns out to be only 5 - 4 = 1, but D is not checked again. Dijkstra says D = 3, while A, C, B, D adds up to 2. When there are negative weights, use another algorithm, such as Bellman-Ford.

Graphs without weights: BFS is enough

When edges have no weights, each edge counts as 1 step, so the shortest path is the one with the fewest edges. BFS uses a queue and visits nodes layer by layer: everything 1 step away first, then 2 steps, and so on. So the first time a node is reached, its distance is the shortest.

The graph roads below has no weights and no directions: A is joined to B and C, and D is joined to B and C. Here's how it runs, starting from A:

Taken from the queue New neighbours and their distance Queue after
A B = 1, C = 1 B, C
B D = 2 C, D
C (D already has a distance) D
D none empty, done
const roads = {
  A: ["B", "C"],
  B: ["A", "D"],
  C: ["A", "D"],
  D: ["B", "C"],
};

function bfsDistances(graph, start) {
  const distance = {};
  distance[start] = 0;
  const queue = [start];

  while (queue.length > 0) {
    const node = queue.shift();
    for (const neighbor of graph[node]) {
      if (distance[neighbor] === undefined) {
        distance[neighbor] = distance[node] + 1;
        queue.push(neighbor);
      }
    }
  }
  return distance;
}

console.log(bfsDistances(roads, "A")); // { A: 0, B: 1, C: 1, D: 2 }

A neighbour that already has a distance is skipped, so each node enters the queue once.

In the exercise, you only want the distance to one target. The rules:

⚠️ Nodes marked too late, and a goal you can't reach

💡 How fast is it? The Dijkstra code above checks every node each time it looks for the cheapest one. For V nodes that's about V × V steps, so O(V²): twice the nodes, roughly four times the time. With a heap (a priority queue), Dijkstra becomes O((V + E) log V), E being the number of edges. BFS is just O(V + E): every node and edge is touched once.

TL;DR: In a weighted graph, every edge has a number (its weight), and the length of a path is the sum of its weights. Dijkstra finds the shortest distances from one starting node: the start's distance is 0, every other node's is ∞ (no path yet). Then take the cheapest node (the smallest distance) that isn't final yet. Its distance becomes final (treated as the shortest), and its neighbours' distances are updated when going through that node is cheaper (relaxation). Repeat until everything is final. Dijkstra needs weights that aren't negative. For negative weights, use Bellman-Ford. In a graph without weights, BFS with a queue already gives the fewest edges. In the exercise, the start node to itself is 0, and an unreachable target is -1.

⚡ A detour can be shorter

Guess first: A to B on the straight road is 4 km, or through C: A to C is 2 km, then C to B is 1 km. Which is shorter?

Through C, only 3 km in total (2 + 1).

Meaning: In a weighted graph, every edge (here a road) has a number called its weight, such as a distance in km. The length of a path is the sum of its edges' weights. The shortest path is the one with the smallest total weight.

⚡ Dijkstra: continue from the cheapest node

Write:

// relaxation: check every neighbour
for (const [next, w] of Object.entries(graph[node])) {
  if (dist[node] + w < dist[next]) {
    dist[next] = dist[node] + w;
  }
}

Meaning: Dijkstra finds the shortest distances from one starting node. dist holds the best distance of each node so far, at first 0 for the start and ∞ for every other node. node is the cheapest node (the smallest distance) that isn't final yet, and when it's taken, its distance becomes final. This code checks each neighbour next of node, with the edge weight w. If going through node is cheaper, the neighbour's distance is replaced. This step is called relaxation. Repeat until everything is final.

⚡ Negative weights, and graphs without weights

Meaning: Dijkstra needs weights that aren't negative, because the distance of a node that's final is assumed never to go down again. With negative weights, use another algorithm, Bellman-Ford. In a graph without weights, BFS (walking layer by layer with a queue) is enough. In the exercise, a target equal to the start means 0, and an unreachable target (no path to it) means -1.

What you will learn