Kodewick
Start learning →
Shortest paths: Dijkstra32 / 50

Shortest paths: Dijkstra

Lesson 32 of 50 · Part 6 · Graphs · about 18 minutes

Dijkstra's algorithm finds single-source shortest paths in a weighted graph: each round it settles the unsettled vertex nearest the start and updates its neighbours' dist, O(n²) with an array, and it goes wrong when an edge is negative.

The route a navigation app gives often isn't the one through the fewest junctions: a straight 7 km road can be longer than one with two turns that comes to 5 km. Put weights on the edges (length, time, cost) and the BFS from a few lessons back is wrong, because it only counts edges. For single-source shortest paths in a weighted graph (from one start to every vertex), the usual tool is Dijkstra's algorithm, which Dijkstra thought up in twenty minutes in a café in 1956 and which the OSPF routing protocol still uses today.

Settle the nearest one each time

Keep dist[v] as "the shortest distance from the start to v known so far": 0 for the start and ∞ for the rest to begin with. Vertices are of two kinds: settled (dist won't change again) and not yet settled. Repeat n times:

  1. Among the unsettled vertices, pick u with the smallest dist, and settle it.
  2. Use u to relax each neighbour v: if dist[u] + w(u, v) < dist[v], lower dist[v] and note prev[v] = u.

Why can the picked u be settled? Suppose there were a shorter way to u. It would start among the settled vertices and at some point pass through an unsettled vertex x before reaching u. But x's dist is no smaller than u's (u is the smallest), and going on from x to u can only add length (no edge weight is negative). So there is no shorter way.

From 0. The number on a vertex is its dist now, green means settled; a thick line is the edge used when settling (prev), and together they make the shortest path tree
Choose one

Undirected graph: A–B 4, A–C 1, C–B 2, B–D 1, C–D 5. Running Dijkstra from A, in what order are the vertices settled?

Choose one

Same graph. Once C is settled and its neighbours relaxed, what are dist of B and D?

Put in orderDrag, or use the arrows

Put Dijkstra's lines in order: set up dist first, then n rounds, each one picking the closest vertex, settling it and relaxing. closest() returns the unsettled vertex with the smallest dist, and relax(u) relaxes u's neighbours; both are already written.

  1. for (int k = 0; k < N; k++) {
  2. done[u] = 1;
  3. int u = closest();
  4. dist[0] = 0;
  5. }
  6. relax(u);
  7. for (int i = 0; i < N; i++) dist[i] = INF;
Should print
0 5 2 9 10 13

In C: the O(n²) array version

Each round finds the smallest of n vertices (O(n)), then scans u's row to relax (O(n)), and there are n rounds: O(n²). It's stored as an adjacency matrix, with INF where there's no edge.

main.c
1#include <stdio.h>2 3#define N 64#define INF 10000000005 6int w[N][N], dist[N], prev[N], done[N];7 8void add(int u, int v, int c) { w[u][v] = w[v][u] = c; }9 10void dijkstra(int s) {11    for (int i = 0; i < N; i++) {12        dist[i] = INF;13        prev[i] = -1;14        done[i] = 0;15    }16    dist[s] = 0;17    for (int k = 0; k < N; k++) {18        int u = -1;19        for (int i = 0; i < N; i++)              // the smallest unsettled20            if (!done[i] && (u == -1 || dist[i] < dist[u]))21                u = i;22        if (dist[u] == INF) break;               // the rest can't be reached23        done[u] = 1;24        for (int v = 0; v < N; v++)              // relax25            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v]) {26                dist[v] = dist[u] + w[u][v];27                prev[v] = u;28            }29    }30}31 32void path(int v) {33    if (prev[v] != -1) {34        path(prev[v]);35        printf(" -> ");36    }37    printf("%d", v);38}39 40int main(void) {41    for (int i = 0; i < N; i++)42        for (int j = 0; j < N; j++)43            w[i][j] = INF;44    add(0, 1, 7); add(0, 2, 2); add(2, 1, 3); add(1, 3, 4);45    add(2, 4, 9); add(3, 4, 1); add(3, 5, 6); add(4, 5, 3);46    dijkstra(0);47    for (int i = 0; i < N; i++)48        printf("dist[%d] = %d\n", i, dist[i]);49    printf("to 5: ");50    path(5);51    printf("\n");52    return 0;53}
Output
dist[0] = 0
dist[1] = 5
dist[2] = 2
dist[3] = 9
dist[4] = 10
dist[5] = 13
to 5: 0 -> 2 -> 1 -> 3 -> 4 -> 5

INF is a thousand million rather than INT_MAX: with INT_MAX, INF + a weight overflows to a negative number and looks "smaller". Here w[u][v] != INF is checked first, and dist[u] can't be INF either, so a thousand million is enough and never overflows.

Guess the outputA wrong guess is fine

Edges 0–1 (10), 0–2 (3), 2–1 (4), 1–3 (2), 2–3 (8), from 0. What is dist?

1#include <stdio.h>2 3#define N 44#define INF 10000000005 6int w[N][N], dist[N], done[N];7 8int main(void) {9    for (int i = 0; i < N; i++)10        for (int j = 0; j < N; j++)11            w[i][j] = INF;12    w[0][1] = w[1][0] = 10;13    w[0][2] = w[2][0] = 3;14    w[2][1] = w[1][2] = 4;15    w[1][3] = w[3][1] = 2;16    w[2][3] = w[3][2] = 8;17    for (int i = 0; i < N; i++) dist[i] = INF;18    dist[0] = 0;19    for (int k = 0; k < N; k++) {20        int u = -1;21        for (int i = 0; i < N; i++)22            if (!done[i] && (u == -1 || dist[i] < dist[u])) u = i;23        done[u] = 1;24        for (int v = 0; v < N; v++)25            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v])26                dist[v] = dist[u] + w[u][v];27    }28    for (int i = 0; i < N; i++) printf("%d ", dist[i]);29    printf("\n");30    return 0;31}
Choose one

Why is this level's array version O(n²) for n vertices?

Choose one

Why does the program use a billion for INF, and not INT_MAX, the biggest value an int holds?

Exercise 1

Find the smallest unsettled

Fill in the first step of each round: among the vertices with done[i] == 0, find u with the smallest dist.

It should print
0 3 1 4 7
exercise1.c
1#include <stdio.h>2 3#define N 54#define INF 10000000005 6int w[N][N], dist[N], done[N];7 8void add(int u, int v, int c) { w[u][v] = w[v][u] = c; }9 10int main(void) {11    for (int i = 0; i < N; i++)12        for (int j = 0; j < N; j++)13            w[i][j] = INF;14    add(0, 1, 4); add(0, 2, 1); add(2, 1, 2); add(1, 3, 1); add(2, 3, 5); add(3, 4, 3);15    for (int i = 0; i < N; i++) dist[i] = INF;16    dist[0] = 0;17    for (int k = 0; k < N; k++) {18        int u = 0;19        // set u = -1 first; i from 0 to N - 1: if unsettled, and u == -1 or dist[i] < dist[u], then u = i20        done[u] = 1;21        for (int v = 0; v < N; v++)22            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v])23                dist[v] = dist[u] + w[u][v];24    }25    for (int i = 0; i < N; i++) printf("%d ", dist[i]);26    printf("\n");27    return 0;28}
Output
Press Run or Ctrl+Enter
Exercise 2

Relax and remember the way

Fill in the relaxation: when dist[u] + w[u][v] is smaller, change dist[v] and note prev[v] = u. The program follows prev back from 5 to collect the path, then prints it forwards.

It should print
0 2 1 3 4 5 (13)
exercise2.c
1#include <stdio.h>2 3#define N 64#define INF 10000000005 6int w[N][N], dist[N], prev[N], done[N];7 8void add(int u, int v, int c) { w[u][v] = w[v][u] = c; }9 10int main(void) {11    for (int i = 0; i < N; i++)12        for (int j = 0; j < N; j++)13            w[i][j] = INF;14    add(0, 1, 7); add(0, 2, 2); add(2, 1, 3); add(1, 3, 4);15    add(2, 4, 9); add(3, 4, 1); add(3, 5, 6); add(4, 5, 3);16    for (int i = 0; i < N; i++) { dist[i] = INF; prev[i] = -1; }17    dist[0] = 0;18    for (int k = 0; k < N; k++) {19        int u = -1;20        for (int i = 0; i < N; i++)21            if (!done[i] && (u == -1 || dist[i] < dist[u])) u = i;22        done[u] = 1;23        for (int v = 0; v < N; v++) {24            // unsettled, an edge, and nearer through u: change dist[v], prev[v] = u25        }26    }27    int p[N], len = 0;28    for (int v = 5; v != -1; v = prev[v]) p[len++] = v;29    for (int i = len - 1; i >= 0; i--) printf("%d ", p[i]);30    printf("(%d)\n", dist[5]);31    return 0;32}
Output
Press Run or Ctrl+Enter

A negative edge breaks it

The proof in the first level leaned on "no edge weight is negative". With a negative edge, a settled vertex can later be overtaken by a path that "goes the long way, then takes a negative edge", but it's settled and won't change. A directed graph with four vertices:

A directed graph where 2 → 1 weighs −3. Dijkstra settles 1 (at 2) first, and only later finds that 0 → 2 → 1 costs just 4 − 3 = 1

Run it, against Bellman-Ford, which copes with negative weights. Bellman-Ford never "settles" anything; it just relaxes every edge, n − 1 rounds, O(n·e):

main.c
1#include <stdio.h>2 3#define N 44#define INF 10000000005 6int w[N][N];7 8void dijkstra(int dist[]) {9    int done[N] = {0};10    for (int i = 0; i < N; i++) dist[i] = INF;11    dist[0] = 0;12    for (int k = 0; k < N; k++) {13        int u = -1;14        for (int i = 0; i < N; i++)15            if (!done[i] && (u == -1 || dist[i] < dist[u])) u = i;16        done[u] = 1;17        for (int v = 0; v < N; v++)18            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v])19                dist[v] = dist[u] + w[u][v];20    }21}22 23void bellman_ford(int dist[]) {24    for (int i = 0; i < N; i++) dist[i] = INF;25    dist[0] = 0;26    for (int k = 0; k < N - 1; k++)              // n - 1 rounds27        for (int u = 0; u < N; u++)              // each round relaxes every edge28            for (int v = 0; v < N; v++)29                if (w[u][v] != INF && dist[u] != INF && dist[u] + w[u][v] < dist[v])30                    dist[v] = dist[u] + w[u][v];31}32 33int main(void) {34    for (int i = 0; i < N; i++)35        for (int j = 0; j < N; j++)36            w[i][j] = INF;37    w[0][1] = 2; w[0][2] = 4; w[2][1] = -3; w[1][3] = 1;   // directed edges38    int d1[N], d2[N];39    dijkstra(d1);40    bellman_ford(d2);41    printf("Dijkstra:     ");42    for (int i = 0; i < N; i++) printf("%d ", d1[i]);43    printf("\nBellman-Ford: ");44    for (int i = 0; i < N; i++) printf("%d ", d2[i]);45    printf("\n");46    return 0;47}
Output
Dijkstra:     0 2 4 3 
Bellman-Ford: 0 1 4 2 

The conclusion: with negative edges, don't use Dijkstra. Nor can you "add the same number to every edge to make them positive": paths with more edges get more added, and the shortest path changes. For negative weights use Bellman-Ford (or SPFA, its queue version); if the graph has a negative cycle, every lap round it is shorter, and there's no shortest path at all.

Choose one

Directed edges 0 → 1 (1), 0 → 2 (3), 2 → 1 (−3). Starting from 0, what dist[1] does Dijkstra give, and what is the real shortest distance?

Choose one

Someone suggests adding 3 to every edge, so there are no negative weights, and then running Dijkstra. Why doesn't that work?

The faster version, and Floyd

The O(n²) bottleneck is scanning everything to find the smallest. Keep the unsettled vertices in a min-heap ordered by dist: finding the smallest becomes O(log n), and each successful relaxation pushes a new (dist, v) into the heap. That's O((n + e) log n) in all, much faster than O(n²) on a sparse graph (e about as big as n): with n at 100,000, n² is ten thousand million, while (n + e) log n is a few million.

For shortest paths between every pair of vertices there's Floyd's algorithm, just three nested loops: d[i][j] = min(d[i][j], d[i][k] + d[k][j]), with k outermost, meaning "allow 0 to k as stops along the way". O(n³), and it copes with negative edges (but not negative cycles).

AlgorithmFindsNegative edgesTime
BFSone source, unweightedn/aO(n + e)
Dijkstra (array)one sourcenoO(n²)
Dijkstra (heap)one sourcenoO((n + e) log n)
Bellman-Fordone sourceyes, and it detects negative cyclesO(n·e)
Floydevery pairyes (no negative cycles)O(n³)

In exams: an exam favourite is "use Dijkstra to find shortest paths from v to every vertex, giving dist and the chosen vertex at each step": fill in the table step by step, as in the first level's figure, remembering each round settles one vertex only. Also "does Dijkstra work with negative weights?" (no) and "why is Floyd's k the outermost loop?".

Choose one

n = 100,000 vertices, e = 200,000 edges, no negative weights, shortest paths from one start to every vertex. Which fits best?

Choose one

200 cities, and you need the shortest path between every pair; a few edges are negative, but there's no negative cycle. What's the least work?

Summary

Take-away

Dijkstra: settle the nearest one each time

  • dist is 0 at the start, ∞ elsewhere; n rounds: pick the smallest unsettled u, settle it, relax its neighbours
  • prev[v] = u remembers the way; walk it back to the start
  • Array O(n²), heap O((n + e) log n)
  • Negative edges make it wrong: use Bellman-Ford; for every pair, Floyd O(n³)
1done[u] = 1;2for (int v = 0; v < N; v++)3    if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v])4        dist[v] = dist[u] + w[u][v], prev[v] = u;