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 nn - 1[from, to, weight]fromtosourcesource
Example 1
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
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.
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.
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}{1, 4}{2, 1}{1, 2}{3, 5}{3, 1}{4, 3}
Keeping the best distance so far
Where does each node's distance live while it can still drop? In an intdistdist[source]Integer.MAX_VALUEint
Picking the closest unsettled node
How do we find the closest unsettled node in each round? The simple way scans distnnn
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}{1, 4}{2, 1}{2, 1}PriorityQueuepoll()
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
Outdated heap entries
What happens to the pair {1, 4}PriorityQueueremove(Object){1, 4}{1, 3}{1, 4}dist[1]
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}{3, 6}
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 distInteger.MAX_VALUE
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]
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}{1, 3, 1}
The code on this graph happens to recover: the new pair {1, 1}[0, 1, 3, 2][0, 2, 3, 3][0, 3, 1, 4, 7]
Java Solution
The method shortestDistances
- First, build the adjacency list
: one emptyadj per node, then a loop overArrayList that addsedges to the list of each edge's{to, weight} node.from - Create the array
, fill it withdist , and setInteger.MAX_VALUE to 0.dist[source] - Create the min-heap
, ordered by distance, and push the pairheap .{source, 0} - While
is not empty, poll the closest pair intoheap andnode . Ifd is larger thand , the pair is stale and the loop moves on.dist[node] - Otherwise
is settled. An inner loop goes over its pairs, each callednode , reads the node the edge leads to intonext , and computesto asnewDist plus the edge's weight. Ifd is smaller thannewDist , it is stored there anddist[to] is pushed onto{to, newDist} .heap - When the heap is empty, a last loop turns every
left inInteger.MAX_VALUE into -1, and the method returnsdist .dist
The main
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:
[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][1, 0, 0, -1][0]
The fourth line, [0, 1, 2, 3]
Complexity
With V nodes (n
- 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
holds one pair for each of the E edges andadj 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.dist
When every edge costs the same, a plain queue can take the place of the heap: see