Shortest paths: Dijkstra and Floyd

Intermediate

Introduction

BFS counts moves, which is right when every move costs the same. Real roads, flights and cables have different costs. Dijkstra's algorithm finds the cheapest route from one start to every vertex when all costs are zero or more. When you need the distance between every pair of vertices and the graph is small, Floyd–Warshall is three loops long.

How it works

Dijkstra with a priority queue

Store the graph as vector<vector<pair<int, int>>>: for each vertex, its (neighbour, weight) pairs. Keep a dist array, large at first, and a priority queue of (distance, vertex) pairs. Take the entry with the smallest distance; for each edge out of it, if going through it is cheaper than the known distance, lower the distance and push the new pair.

priority_queue takes the largest item first, so push negated distances to get the smallest first. When an entry comes out that is worse than the best known distance, it is out of date: skip it. This is O((n + m) log n), fast enough for 10⁵ vertices.

The reason it works: the smallest unprocessed distance cannot be improved later, because any other route would first pass through a vertex that is at least as far away, and costs are not negative. With a negative edge this argument fails, and Dijkstra can give wrong answers.

All pairs with Floyd–Warshall

Keep a matrix d[i][j] of distances, 0 on the diagonal and a huge value where there is no edge. For each middle vertex k, for each pair i, j, check whether going through k is shorter. The three loops run in O(n³), so n up to about 400 is fine, and then any pair is answered by one lookup.

SituationUseCost
all costs equalBFSO(n + m)
costs differ, one startDijkstraO((n + m) log n)
every pair, n up to 400Floyd–WarshallO(n³)

Counting shortest paths

While running Dijkstra, keep ways[v], the number of cheapest paths to v. When you find a strictly shorter distance to v through u, set ways[v] = ways[u]. When you find an equal distance, add: ways[v] += ways[u] (modulo a prime for big answers).

Use a safe infinity. Pick a value that is larger than any real distance but small enough that adding two of them does not overflow. In Floyd, INF + INF must still fit.

Example

#include <iostream>
#include <queue>
#include <vector>
using namespace std;

int main() {
    int n = 4;
    vector<vector<pair<int, int>>> adj(n);
    adj[0].push_back({1, 4});   // an edge 0 -> 1 with weight 4
    adj[0].push_back({2, 1});
    adj[2].push_back({1, 2});
    adj[1].push_back({3, 1});
    adj[2].push_back({3, 5});
    vector<long long> dist(n, 1000000000);
    priority_queue<pair<long long, int>> pq;
    dist[0] = 0;
    pq.push({0, 0});
    while (!pq.empty()) {
        long long d = -pq.top().first;
        int u = pq.top().second;
        pq.pop();
        if (d > dist[u]) continue;   // out of date
        for (auto& edge : adj[u]) {
            int v = edge.first, w = edge.second;
            if (dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                pq.push({-dist[v], v});
            }
        }
    }
    for (int v = 0; v < n; v++) cout << dist[v] << " ";
    cout << "\n";
    return 0;
}
Open in compiler

The graph has four vertices and five directed edges. Dijkstra starts at vertex 0 and prints the cheapest cost to each vertex.

Line by line

  • adj[0].push_back({1, 4}) is an edge from 0 to 1 that costs 4.
  • dist starts large; dist[0] = 0 and (0, 0) goes into the queue.
  • -pq.top().first undoes the negation to get the real distance d.
  • if (d > dist[u]) continue; skips an entry that is out of date.
  • When dist[u] + w < dist[v], a cheaper path to v was found, so v is updated and pushed.

Expected result

0 3 1 4 

In the real world

Maps and navigation apps run Dijkstra-like searches (with many speed-ups) to find the quickest route. Network routing protocols such as OSPF use Dijkstra to choose paths through a network of links. Game characters use a close cousin, A*, to move around obstacles. Floyd–Warshall answers all-pairs questions on small networks, like the cheapest transfer between any two stations of a metro.

Common mistakes

  • Using Dijkstra with negative edge weights.
  • Forgetting the stale-entry check, which makes the algorithm much slower.
  • Pushing positive distances into the default priority_queue, which then gives the largest first.
  • Using int for distances that can pass 2 × 10⁹.
  • Setting INF so large that INF + INF overflows.

Best practices

  • Use long long for distances.
  • Write the stale check as the first line after the pop.
  • Choose BFS when all edges cost the same.
  • Keep INF around 10¹⁸ for Dijkstra and 10¹² for Floyd, and check the sum before relaxing.
  • Read the limits: n up to 400 means Floyd, 10⁵ means Dijkstra.

Summary

Dijkstra pops the closest unprocessed vertex and relaxes its edges, in O((n + m) log n) with a priority queue of negated distances. Floyd–Warshall gives every pair in O(n³) with three loops. Counting paths adds a second array to Dijkstra.

Quick check

1. Why push -dist into priority_queue for Dijkstra?
2. An entry with distance d comes out, but dist[u] < d already. What do you do?
3. Dijkstra can fail when the graph has:
4. n = 300 and you need the distance between any two vertices. What fits?

Key takeaways

  • BFS handles equal costs; Dijkstra handles different non-negative costs
  • Dijkstra costs O((n + m) log n) with a priority queue
  • A stale entry (d bigger than dist[u]) is skipped
  • Floyd is three loops and is fine up to about n = 400

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.