Graph - Dijkstra's Shortest Path Algorithm

Find the shortest distance from one node to every other node of a graph whose edge weights are never negative.

Take a directed graph whose n nodes are numbered 0 to n - 1. Each edge is written as [from, to, weight]: it can be followed only from from to to, and its weight, never negative, is the cost of following it. The distance of a route is the sum of its edge weights. Given the edges and a source node, return the shortest distance from source to every node, with -1 for a node that no route reaches.

Example 1
Input: n = 5, edges = [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 3, 5], [3, 4, 3]], source = 0
Output: [0, 3, 1, 4, 7]
Explanation: The edge 0 → 1 costs 4, but the route 0 → 2 → 1 costs 1 + 2 = 3.
Example 2
Input: n = 4, edges = [[0, 1, 2], [1, 2, 0], [2, 0, 1]], source = 1
Output: [1, 0, 0, -1]
Explanation: From node 1, the edge 1 → 2 costs 0 and then 2 → 0 costs 1. No edge leads to node 3.
Solution

The Idea

Picture Example 1 as five towns, 0 to 4, linked by one-way roads. The towns are the graph's nodes, the roads are its edges, and each weight is the number of minutes a road takes. You start in town 0 and want the quickest time to every other town.

Two roads leave town 0: one to town 1 that takes 4 minutes, and one to town 2 that takes 1. It is tempting to write down 4 for town 1 right away. But a road from town 2 reaches town 1 in 2 more minutes, so 0 → 2 → 1 takes 3 and beats the direct road. A route found early can lose to a longer chain of cheaper roads. So when can we trust a distance?

Look at town 2. Of the two towns reached so far, it is the closer one, at 1 minute. Any other route to town 2 would have to start with the road to town 1, which already costs 4, and the roads after it can only add minutes, because no weight is negative. So 1 is town 2's final distance. A node whose distance is known to be final is called settled.

The same reasoning works at every round: among the nodes reached but not yet settled, the one with the smallest distance is settled next. Then each edge leaving it is checked. If following that edge gives the node at its far end a shorter distance than it has so far, the distance is lowered, which is called relaxing the edge. The picture below shows where this ends up for Example 1.

Example 1 as a graph of five nodes, 0 to 4. Orange arrows 0 to 2 (1), 2 to 1 (2), 1 to 3 (1) and 3 to 4 (3) are the shortest routes from 0; the dashed edges 0 to 1 (4) and 2 to 3 (5) are not used. The final distances are 0, 3, 1, 4 and 7, and the nodes are settled in the order 0, 2, 1, 3, 4.

Each node carries a badge with its final distance, and the orange arrows are the edges that the shortest routes from 0 follow. The row at the bottom, labelled "order in which the nodes are settled", follows the rounds. Node 0 is settled first, at 0, and its edges give node 1 a distance of 4 and node 2 a distance of 1. Node 2 is closer, so it is settled next.

Node 2's edge of weight 2 lowers node 1 from 4 to 3, and its edge of weight 5 gives node 3 a distance of 6. Node 1 is settled at 3, and its edge of weight 1 lowers node 3 from 6 to 4. Node 3 is settled at 4 and gives node 4 a distance of 4 + 3 = 7, and node 4 is settled last.

The two dashed edges, marked "edges no shortest route uses", are 0 → 1 with weight 4 and 2 → 3 with weight 5. They each gave a node a distance for a while, until a shorter route replaced it. Settling the closest node and relaxing its edges, round after round, is Dijkstra's algorithm, named after Edsger Dijkstra, who published it in 1959.

Solution Approach

Five choices shape the code: how to store the edges, where to keep the distances, how to pick the closest unsettled node, what to do with entries that go out of date, and when to stop. Two traps, a shortcut in the code and a negative weight in the input, give wrong answers.

Storing the edges

Which edges leave a node? Settling a node means looking at exactly those, so the edges are grouped by the node they start from. Each node gets a list of {to, weight} pairs, one for each edge leaving it, and this list of lists is called an adjacency list. In Example 1, node 0's list holds {1, 4} and {2, 1}. Node 2's list holds {1, 2} and {3, 5}, node 1's holds {3, 1}, node 3's holds {4, 3}, and node 4's list is empty.

Keeping the best distance so far

Where does each node's distance live while it can still drop? In an int array named dist, with dist[source] set to 0. Every other entry starts at Integer.MAX_VALUE, the largest int, which stands for "not reached yet". Any real route is shorter, so the first edge that reaches a node always wins the comparison.

Picking the closest unsettled node

How do we find the closest unsettled node in each round? The simple way scans dist across all n nodes, and with one round per node that is n Ɨ n checks in all, even when each node has only one or two edges.

A min-heap avoids the scan. It is a collection that hands back the entry with the smallest distance first, in whatever order the entries went in. Here each entry is a pair {node, distance}. After node 0 is settled, the heap holds {1, 4} and {2, 1}, node 1 at distance 4 and node 2 at distance 1, and hands back {2, 1} first. Each push or poll takes a number of steps that grows with the logarithm of the heap's size. In Java the heap is a PriorityQueue of these pairs, compared by the distance at index 1, so poll() returns the closest pair. Each time an edge lowers a node's distance, a new pair with that distance goes onto the heap, which is created like this:

Java
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));

Outdated heap entries

What happens to the pair {1, 4} once node 1's distance drops to 3? PriorityQueue has no method to lower an entry's distance, and its remove(Object) takes linear time, so the code leaves {1, 4} where it is and pushes {1, 3} as well. When {1, 4} comes out later, its 4 is larger than dist[1], which is 3, so the pair is skipped. A pair whose distance is no longer the node's best is called a stale entry.

A run that prints every poll on Example 1 shows seven polls. Five of them settle the nodes in the order of the picture's bottom row, and two, {1, 4} and {3, 6}, are skipped as stale.

When the loop stops

The loop runs until the heap is empty, because then no node is waiting with a distance that could still spread. A node that no edge reaches never gets a pair, so its dist entry still holds Integer.MAX_VALUE, and it becomes -1 in the answer. If only one target node's distance is wanted, the loop can stop as soon as that node is settled, since its distance is final from then on.

Fixing a distance the first time it is found

Why not give each node a distance the first time an edge reaches it and never change it? Breadth-first search, which explores a graph one edge-step at a time, works that way, and it is right when every edge costs the same. A run of the heap code changed that way on Example 1 returns [0, 4, 1, 6, 9]. Node 1 keeps the 4 from the edge 0 → 1, and the error carries on to node 3 and node 4.

Why weights must not be negative

Settling rests on edges only adding to a distance. Take the edges {0, 1, 2}, {0, 2, 3}, {2, 1, -2} and {1, 3, 1} from source 0. Node 1 is settled at 2, but node 2, settled next at 3, lowers it through the edge of weight -2 to 3 - 2 = 1. A settled distance was not final after all.

The code on this graph happens to recover: the new pair {1, 1} goes onto the heap, node 1 is settled a second time, and the result is [0, 1, 3, 2]. A version that marks each node as done at its first poll and never handles it again returns [0, 2, 3, 3] instead, though it gives [0, 3, 1, 4, 7] on Example 1. Neither version is guaranteed to be right with negative weights. For such graphs, the Bellman-Ford algorithm relaxes every edge over and over instead of settling nodes.

Java Solution

The method shortestDistances works in these steps:

  1. First, build the adjacency list adj: one empty ArrayList per node, then a loop over edges that adds {to, weight} to the list of each edge's from node.
  2. Create the array dist, fill it with Integer.MAX_VALUE, and set dist[source] to 0.
  3. Create the min-heap heap, ordered by distance, and push the pair {source, 0}.
  4. While heap is not empty, poll the closest pair into node and d. If d is larger than dist[node], the pair is stale and the loop moves on.
  5. Otherwise node is settled. An inner loop goes over its pairs, each called next, reads the node the edge leads to into to, and computes newDist as d plus the edge's weight. If newDist is smaller than dist[to], it is stored there and {to, newDist} is pushed onto heap.
  6. When the heap is empty, a last loop turns every Integer.MAX_VALUE left in dist into -1, and the method returns dist.

The main method runs both examples, a single node with no edges, a chain of three edges of weight 1 next to one edge of weight 10, and Example 1 again from source 3.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

public class Dijkstra {

    // edges[i] = {from, to, weight}, directed, weight >= 0. A node never reached gets -1.
    public static int[] shortestDistances(int n, int[][] edges, int source) {
        List<List<int[]>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            adj.get(edge[0]).add(new int[] {edge[1], edge[2]});      // {to, weight}
        }

        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);                         // not reached yet
        dist[source] = 0;
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
        heap.add(new int[] {source, 0});                              // {node, distance}

        while (!heap.isEmpty()) {
            int[] top = heap.poll();
            int node = top[0];
            int d = top[1];
            if (d > dist[node]) {
                continue;                 // stale entry: a shorter one was already used
            }
            for (int[] next : adj.get(node)) {
                int to = next[0];
                int newDist = d + next[1];
                if (newDist < dist[to]) {     // a shorter route to "to"
                    dist[to] = newDist;
                    heap.add(new int[] {to, newDist});
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if (dist[i] == Integer.MAX_VALUE) {
                dist[i] = -1;
            }
        }
        return dist;
    }

    public static void main(String[] args) {
        int[][] example1 = {{0, 1, 4}, {0, 2, 1}, {2, 1, 2}, {1, 3, 1}, {2, 3, 5}, {3, 4, 3}};
        System.out.println(Arrays.toString(shortestDistances(5, example1, 0)));
        int[][] example2 = {{0, 1, 2}, {1, 2, 0}, {2, 0, 1}};
        System.out.println(Arrays.toString(shortestDistances(4, example2, 1)));
        System.out.println(Arrays.toString(shortestDistances(1, new int[0][], 0)));
        int[][] chain = {{0, 3, 10}, {0, 1, 1}, {1, 2, 1}, {2, 3, 1}};
        System.out.println(Arrays.toString(shortestDistances(4, chain, 0)));
        System.out.println(Arrays.toString(shortestDistances(5, example1, 3)));
    }
}

Running it prints:

Output
[0, 3, 1, 4, 7]
[1, 0, 0, -1]
[0]
[0, 1, 2, 3]
[-1, -1, -1, 0, 3]

The first line, [0, 3, 1, 4, 7], matches the badges in the picture. The second, [1, 0, 0, -1], is Example 2 from source 1. Node 2 gets 0 through the edge of weight 0, which the code treats like any other weight, and node 3, with no edge leading to it, ends at -1. In the third line, the single node is its own source, so the answer is [0].

The fourth line, [0, 1, 2, 3], is the chain. Settling node 0 first gives node 3 a distance of 10 through its direct edge, and settling node 2 later lowers it to 1 + 1 + 1 = 3. The last line runs Example 1 from node 3. Edges only go one way, so nodes 0, 1 and 2 cannot be reached from node 3 and print -1, while node 4 is 3 away.

Complexity

With V nodes (n in the code) and E edges, the work is building the lists plus one heap push and one poll for each time an edge lowers a distance.

  • Time: O((V + E) log V), because each node's edges are looked at once, when it is settled, giving at most E + 1 heap pushes and as many polls at O(log E) each. When no two edges join the same two nodes in the same direction, E is below V², so log E is at most 2 log V.
  • Space: O(V + E), because adj holds one pair for each of the E edges and dist one number for each of the V nodes. The heap can hold up to E + 1 pairs at once, since stale pairs stay in it until they are polled.

When every edge costs the same, a plain queue can take the place of the heap: see Shortest Path in Unweighted Graph (BFS).