Kodewick
Start learning →
Shortest paths: Dijkstra34 / 52

Shortest paths: Dijkstra

Lesson 34 of 52 · Part 6 · Graphs · about 20 minutes

Dijkstra's algorithm finds shortest paths from one start when no edge is negative: it settles the nearest unsettled vertex and updates its neighbours' dist, O(n²) with arrays or faster with priority_queue and greater.

The route a navigation app gives you is often not the one with the fewest junctions: a straight 7 km road can be longer than a 5 km route with two turns. Once edges carry weights (length, time, cost), BFS from earlier 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 worked out in twenty minutes in a café in 1956; the OSPF routing protocol still runs it today. This lesson first writes the O(n²) version with arrays, then the way C++ code usually does it: priority_queue with greater.

Settle the nearest one each time

dist[v] holds "the shortest distance from the start to v known so far": 0 for the start, ∞ for everything else. Vertices are either settled (dist will not change again) or not yet settled. Repeat n times:

  1. Among the unsettled vertices, take the one with the smallest dist, u, and settle it.
  2. Relax each neighbour v of u: if dist[u] + w(u, v) < dist[v], lower dist[v] and record prev[v] = u.

Why can u be settled? Suppose there were a shorter path to u. It starts from settled vertices and must pass some 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 only adds length (no edge is negative). So there is no shorter path.

From 0. The number on a vertex is its current dist; green means settled; a thick line is the edge used when it was settled (prev), and together they form 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?

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] = true;
  3. int u = closest();
  4. dist[0] = 0;
  5. }
  6. relax(u);
  7. dist.assign(n, INF);
Should print
0 5 2 9 10 13

The array version: O(n²)

Each round scans n vertices for the smallest (O(n)) and then scans u's row to relax (O(n)), for n rounds: O(n²). The graph is an adjacency matrix vector<vector<int>> with INF where there is no edge; dist, prev and done are vectors too, passed to the function by reference.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7void dijkstra(const vector<vector<int>>& w, int s, vector<int>& dist, vector<int>& prev) {8    int n = w.size();9    dist.assign(n, INF);10    prev.assign(n, -1);11    vector<bool> done(n, false);12    dist[s] = 0;13    for (int k = 0; k < n; k++) {14        int u = -1;15        for (int i = 0; i < n; i++)              // the smallest unsettled one16            if (!done[i] && (u == -1 || dist[i] < dist[u]))17                u = i;18        if (dist[u] == INF) break;               // the rest can't be reached19        done[u] = true;20        for (int v = 0; v < n; v++)              // relax21            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v]) {22                dist[v] = dist[u] + w[u][v];23                prev[v] = u;24            }25    }26}27 28void printPath(const vector<int>& prev, int v) {29    if (prev[v] != -1) {30        printPath(prev, prev[v]);31        cout << " -> ";32    }33    cout << v;34}35 36int main() {37    int n = 6;38    vector<vector<int>> w(n, vector<int>(n, INF));39    auto add = [&](int u, int v, int c) { w[u][v] = w[v][u] = c; };40    add(0, 1, 7); add(0, 2, 2); add(2, 1, 3); add(1, 3, 4);41    add(2, 4, 9); add(3, 4, 1); add(3, 5, 6); add(4, 5, 3);42    vector<int> dist, prev;43    dijkstra(w, 0, dist, prev);44    for (int i = 0; i < n; i++)45        cout << "dist[" << i << "] = " << dist[i] << "\n";46    cout << "to 5: ";47    printPath(prev, 5);48    cout << "\n";49    return 0;50}
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 billion, not INT_MAX: INT_MAX + a weight overflows to a negative number, which looks "smaller". Here w[u][v] != INF is checked first and dist[u] is never INF at that point, so a billion is enough and nothing overflows. prev is only ever a parameter or a local: a global named prev clashes with std::prev, which using namespace std; brings in.

Guess the outputA wrong guess is fine

Edges 0–1 (10), 0–2 (3), 2–1 (4), 1–3 (2), 2–3 (8), starting from 0: what is dist?

1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7int main() {8    int n = 4;9    vector<vector<int>> w(n, vector<int>(n, INF));10    w[0][1] = w[1][0] = 10;11    w[0][2] = w[2][0] = 3;12    w[2][1] = w[1][2] = 4;13    w[1][3] = w[3][1] = 2;14    w[2][3] = w[3][2] = 8;15    vector<int> dist(n, INF);16    vector<bool> done(n, false);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] = true;23        for (int v = 0; v < n; v++)24            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v])25                dist[v] = dist[u] + w[u][v];26    }27    for (int d : dist) cout << d << " ";28    cout << "\n";29    return 0;30}
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 vertex

Complete the first step of each round: among the vertices with done[i] false, find u with the smallest dist.

It should print
0 3 1 4 7
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7int main() {8    int n = 5;9    vector<vector<int>> w(n, vector<int>(n, INF));10    auto add = [&](int u, int v, int c) { w[u][v] = w[v][u] = c; };11    add(0, 1, 4); add(0, 2, 1); add(2, 1, 2); add(1, 3, 1); add(2, 3, 5); add(3, 4, 3);12    vector<int> dist(n, INF);13    vector<bool> done(n, false);14    dist[0] = 0;15    for (int k = 0; k < n; k++) {16        int u = 0;17        // set u = -1; for i from 0 to n - 1: if unsettled and (u == -1 or dist[i] < dist[u]), u = i18        done[u] = true;19        for (int v = 0; v < n; v++)20            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v])21                dist[v] = dist[u] + w[u][v];22    }23    for (int d : dist) cout << d << " ";24    cout << "\n";25    return 0;26}
Output
Press Run or Ctrl+Enter

Negative edges break 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; 2 → 1 weighs −3. Dijkstra settles 1 (2) first, and only later finds that 0 → 2 → 1 costs 4 − 3 = 1

Run it next to Bellman-Ford, which handles negative edges. Bellman-Ford settles nothing; it just relaxes every edge n − 1 times, O(n·e):

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7vector<int> dijkstra(const vector<vector<int>>& w) {8    int n = w.size();9    vector<int> dist(n, INF);10    vector<bool> done(n, false);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] = true;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    return dist;22}23 24vector<int> bellmanFord(const vector<vector<int>>& w) {25    int n = w.size();26    vector<int> dist(n, INF);27    dist[0] = 0;28    for (int k = 0; k < n - 1; k++)              // n - 1 rounds29        for (int u = 0; u < n; u++)              // each round relaxes every edge30            for (int v = 0; v < n; v++)31                if (w[u][v] != INF && dist[u] != INF && dist[u] + w[u][v] < dist[v])32                    dist[v] = dist[u] + w[u][v];33    return dist;34}35 36int main() {37    vector<vector<int>> w(4, vector<int>(4, INF));38    w[0][1] = 2; w[0][2] = 4; w[2][1] = -3; w[1][3] = 1;   // directed edges39    cout << "Dijkstra:     ";40    for (int d : dijkstra(w)) cout << d << " ";41    cout << "\nBellman-Ford: ";42    for (int d : bellmanFord(w)) cout << d << " ";43    cout << "\n";44    return 0;45}
Output
Dijkstra:     0 2 4 3 
Bellman-Ford: 0 1 4 2 

The rule: with negative edges, don't use Dijkstra. Nor can you "add a constant to every edge to make them positive": paths with more edges get more added, so the shortest path changes. With negative edges use Bellman-Ford (or its queue-based variant SPFA); if the graph has a negative cycle, each lap makes the path shorter, and no shortest path exists 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?

With the STL

The O(n²) bottleneck is the scan for the smallest. With a min-heap, finding it costs O(log n). In C++ that is priority_queue: it is a max-heap by default; give greater<P> as the third template argument to make it a min-heap. The heap holds pair<int, int> with the distance first, the vertex second, because a pair compares first by first. The graph becomes an adjacency list vector<vector<P>>, with g[u] holding (v, w).

priority_queue cannot change an element already inside it. 1 went in with 7, and later we found 5: what then? Don't change it: push a new (5, 1); the old (7, 1) stays in the heap, and when it is popped we see 7 > dist[1], know it is stale, and skip it. This is called lazy deletion.

Inside a priority_queue is a vector kept as a binary heap (libstdc++ uses push_heap / pop_heap): index 0 is the top, and i's children are at 2i + 1 and 2i + 2. In the figure, the heap row is that vector in its true order, not sorted:

heap

The same graph, with a priority_queue. The row below is the heap's vector in its true order, (distance,vertex), index 0 at the top
main.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5#include <utility>6using namespace std;7 8const int INF = 1000000000;9typedef pair<int, int> P;10 11int main() {12    int n = 6;13    vector<vector<P>> g(n);                      // g[u] holds (v, w)14    auto add = [&](int u, int v, int w) {15        g[u].push_back({v, w});16        g[v].push_back({u, w});17    };18    add(0, 1, 7); add(0, 2, 2); add(2, 1, 3); add(1, 3, 4);19    add(2, 4, 9); add(3, 4, 1); add(3, 5, 6); add(4, 5, 3);20 21    vector<int> dist(n, INF);22    priority_queue<P, vector<P>, greater<P>> pq;  // a min-heap of (distance, vertex)23    dist[0] = 0;24    pq.push({0, 0});25    int pops = 0, stale = 0;26    while (!pq.empty()) {27        int d = pq.top().first, u = pq.top().second;28        pq.pop();29        pops++;30        if (d > dist[u]) {                       // stale: u was handled with a shorter distance31            stale++;32            continue;33        }34        for (const P& e : g[u]) {35            int v = e.first, w = e.second;36            if (d + w < dist[v]) {37                dist[v] = d + w;38                pq.push({dist[v], v});39            }40        }41    }42    for (int i = 0; i < n; i++) cout << dist[i] << " ";43    cout << "\n" << pops << " pops, " << stale << " of them stale and skipped\n";44    return 0;45}
Output
0 5 2 9 10 13 
9 pops, 3 of them stale and skipped

Each edge adds at most one element to the heap, so it holds at most e, and each push / pop is O(log e). In total O((n + e) log n) (log e is at most 2 log n). On a sparse graph (e about n) this is far faster than O(n²): with n = 100 000, n² is 10 billion, while (n + e) log n is a few million.

Common traps:

  • Forgetting greater<P>: a max-heap pops the farthest first. The result is still right (lazy deletion saves it), but the same vertex is popped and relaxed again and again, which is much slower. Some people skip greater and push {-d, v}, negating it again when they take it out.
  • The pair order: the adjacency list holds (v, w), the heap holds (distance, vertex), the other way round. Mix them up and the heap sorts by vertex number.
  • if (d > dist[u]) continue; must stay. Without it the result is still right, but a stale vertex relaxes all its edges again.
Exercise 2

With the heap: relax and record the path

This is the priority_queue version. Complete the relaxation: when d + w < dist[v], update dist[v], record prev[v] = u, and push (dist[v], v). The program then follows prev back from 5, collects the path and prints it reversed.

It should print
0 2 1 3 4 5 (13)
exercise2.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5#include <utility>6#include <algorithm>7using namespace std;8 9const int INF = 1000000000;10typedef pair<int, int> P;11 12int main() {13    int n = 6;14    vector<vector<P>> g(n);15    auto add = [&](int u, int v, int w) { g[u].push_back({v, w}); g[v].push_back({u, w}); };16    add(0, 1, 7); add(0, 2, 2); add(2, 1, 3); add(1, 3, 4);17    add(2, 4, 9); add(3, 4, 1); add(3, 5, 6); add(4, 5, 3);18    vector<int> dist(n, INF), prev(n, -1);19    priority_queue<P, vector<P>, greater<P>> pq;20    dist[0] = 0;21    pq.push({0, 0});22    while (!pq.empty()) {23        int d = pq.top().first, u = pq.top().second;24        pq.pop();25        if (d > dist[u]) continue;26        for (const P& e : g[u]) {27            int v = e.first, w = e.second;28            // shorter through u: update dist[v], prev[v] = u, push it29        }30    }31    vector<int> path;32    for (int v = 5; v != -1; v = prev[v]) path.push_back(v);33    reverse(path.begin(), path.end());34    for (int v : path) cout << v << " ";35    cout << "(" << dist[5] << ")\n";36    return 0;37}
Output
Press Run or Ctrl+Enter
Guess the outputA wrong guess is fine

The min-heap holds pairs. In what order do they come out?

1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5#include <utility>6using namespace std;7 8typedef pair<int, int> P;9 10int main() {11    priority_queue<P, vector<P>, greater<P>> pq;12    pq.push({5, 1});13    pq.push({2, 3});14    pq.push({7, 0});15    pq.push({2, 1});16    while (!pq.empty()) {17        cout << pq.top().first << "," << pq.top().second << " ";18        pq.pop();19    }20    cout << "\n";21    return 0;22}

All pairs with Floyd, and which algorithm to pick

For shortest paths between every pair of vertices there is Floyd's algorithm, just three nested loops: d[i][j] = min(d[i][j], d[i][k] + d[k][j]), with k in the outermost loop, meaning "vertices 0 to k may be used as stopovers". O(n³); it handles negative edges (but not negative cycles).

AlgorithmFindsNegative edgesTime
BFSsingle source, unweightednot relevantO(n + e)
Dijkstra (array)single sourcenoO(n²)
Dijkstra (priority_queue)single sourcenoO((n + e) log n)
Bellman-Fordsingle sourceyes, and it detects negative cyclesO(n·e)
Floydall pairsyes (no negative cycles)O(n³)

In interviews: "network delay time", "cheapest flights", "path with maximum probability" are all Dijkstra in disguise. Make three points clear: priority_queue<P, vector<P>, greater<P>> holds (distance, vertex); stale entries are skipped when popped (lazy deletion, because a priority_queue can't change an element in the middle); and why negative edges are not allowed. Give the complexity as O((n + e) log n). Exams instead ask you to "write dist and the chosen vertex at each step": fill a table round by round as in the first picture, settling exactly one vertex per round.

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; each time take the smallest unsettled u, settle it, relax its neighbours
  • prev[v] = u records the path; walk it back to the start
  • Array O(n²); priority_queue + greater O((n + e) log n)
  • The heap holds (distance, vertex); stale entries are skipped when popped (lazy deletion)
  • Negative edges make it wrong: use Bellman-Ford; for all pairs, Floyd O(n³)
1while (!pq.empty()) {2    int d = pq.top().first, u = pq.top().second; pq.pop();3    if (d > dist[u]) continue;                 // stale4    for (const P& e : g[u]) if (d + e.second < dist[e.first])5        dist[e.first] = d + e.second, pq.push({dist[e.first], e.first});6}