Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Shortest Paths: Dijkstra, Bellman–Ford, Floyd–Warshall

The cheapest way from A to B, with and without negative edges.

A phone finds the fastest route across a continent in a fraction of a second, a trading system spots a loop of exchange rates that returns more money than it started with, and a router recomputes its tables after a link fails. All three are shortest-path problems, solved by three algorithms built on one primitive: relax an edge.

What you’ll learn

  • Define single-source, single-pair and all-pairs shortest paths, explain edge relaxation and the triangle inequality, and distinguish negative edges from negative cycles.
  • Implement Dijkstra's algorithm with a binary heap and lazy deletion, prove that settled distances are final, and state its O((n+m)log⁡n)O((n + m)\log n) bound.
  • Run Bellman–Ford in O(nm)O(nm), explain why n−1n - 1 rounds suffice, and detect negative cycles.
  • Derive Floyd–Warshall's O(n3)O(n^3) recurrence, explain why the loop over intermediate vertices must be outermost, and reconstruct paths.
  • Choose the right algorithm from the weights and queries of a problem, and avoid the classic bugs.

Distances, relaxation and the triangle inequality

Take a directed graph with edge weights w(u,v)w(u, v). The weight of a path is the sum of its edge weights, and the distance δ(s,v)\delta(s, v) is the smallest weight of a path from ss to vv, or ∞\infty if there is none. A shortest-path problem comes in three shapes: single pair (ss to tt), single source (SSSP: ss to every vertex) and all pairs (APSP). No known algorithm solves the single-pair problem asymptotically faster in the worst case than single source, so that is where the algorithms start.

Every algorithm here keeps an estimate d[v]≥δ(s,v)d[v] \ge \delta(s, v) and improves it with one primitive, relaxation:

relax(u,v):if d[u]+w(u,v)<d[v] then d[v]←d[u]+w(u,v),  parent[v]←u\textsf{relax}(u, v):\quad \text{if } d[u] + w(u, v) < d[v] \text{ then } d[v] \leftarrow d[u] + w(u, v),\ \ \text{parent}[v] \leftarrow u
Relaxation never pushes d[v]d[v] below the true distance, because the new value is the weight of a real path. When no edge can be relaxed any more, every d[v]d[v] satisfies the triangle inequality d[v]≤d[u]+w(u,v)d[v] \le d[u] + w(u, v), and the estimates are exact. The algorithms differ only in which edges they relax, and in what order.

Negative edges versus negative cycles. Negative weights are fine in themselves: they model gains, refunds or rewards. What breaks the problem is a negative cycle reachable from ss: going around it again and again drives the cost to −∞-\infty, so distances beyond it are undefined. Forbidding repeated vertices does not rescue it, because the shortest simple path with negative cycles present is NP-hard.

Think first Why does a single negative edge in an undirected graph already break Bellman–Ford, which handles negative edges in directed graphs?

An undirected edge {u,v}\{u, v\} of weight ww is two arcs, u→vu \to v and v→uv \to u. If w<0w < 0, the round trip u→v→uu \to v \to u is a negative cycle of weight 2w2w. Undirected graphs with negative weights need different techniques, based on matching, which is why negative weights appear almost always in directed problems.

Dijkstra’s algorithm: settle the closest vertex

When every weight is non-negative, Dijkstra's algorithm (1959) grows a set of settled vertices whose distances are final. At each step it settles the unsettled vertex with the smallest estimate and relaxes the edges leaving it. A priority queue finds that vertex; with Python's heapq, the simplest correct version pushes a new entry whenever an estimate improves and skips the outdated copies when they surface (lazy deletion).

python
import heapq

def dijkstra(n, adj, s):
    """adj[u] = [(v, w), ...] with every w >= 0. Returns distances and parents."""
    INF = float('inf')
    dist, parent = [INF] * n, [-1] * n
    dist[s] = 0
    heap = [(0, s)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                  # stale entry: u was settled with a smaller key
        for v, w in adj[u]:
            if d + w < dist[v]:       # relax u -> v
                dist[v], parent[v] = d + w, u
                heapq.heappush(heap, (dist[v], v))
    return dist, parent

Every edge is relaxed once, from the moment its tail is settled, so the heap receives at most m+1m + 1 entries and each operation costs O(log⁡m)=O(log⁡n)O(\log m) = O(\log n): O((n+m)log⁡n)O((n + m)\log n) in the worst case. Follow parent back from any vertex to read its path.

DerivationProof
  1. s⇝x→y⇝u,dist[x]=δ(s,x)s \rightsquigarrow x \to y \rightsquigarrow u, \qquad \text{dist}[x] = \delta(s, x)

    Suppose not, and let uu be the first vertex settled with dist[u]>δ(s,u)\text{dist}[u] > \delta(s, u). Take a shortest path from ss to uu, let yy be its first vertex that is not yet settled, and xx the vertex before yy, which is settled and therefore exact:

  2. dist[y]≤δ(s,x)+w(x,y)=δ(s,y)\text{dist}[y] \le \delta(s, x) + w(x, y) = \delta(s, y)

    When xx was settled, the edge x→yx \to y was relaxed, and x→yx \to y lies on a shortest path:

  3. δ(s,y)≤δ(s,u)<dist[u]\delta(s, y) \le \delta(s, u) < \text{dist}[u]

    Here the weights must be non-negative: the rest of the path, from yy to uu, cannot cost less than zero:

  4. dist[y]<dist[u]  ⟹  y is settled before u\text{dist}[y] < \text{dist}[u] \;\Longrightarrow\; y \text{ is settled before } u

    So dist[y]<dist[u]\text{dist}[y] < \text{dist}[u] with yy unsettled, and the heap would have popped yy before uu, a contradiction.

Predict before you look

Edges: S→AS \to A 4, S→BS \to B 1, B→AB \to A 2, A→CA \to C 1, B→CB \to C 5, C→DC \to D 3, A→DA \to D 6, D→TD \to T 1, C→TC \to T 6. What is the distance from SS to TT?

Show the answer

8

Dijkstra settles SS (0), BB (1), AA (3, through BB, beating the direct 4), CC (4), DD (7) and TT (8). The shortest path is S→B→A→C→D→TS \to B \to A \to C \to D \to T, five edges, although S→A→D→TS \to A \to D \to T uses only three.

Priority queueTimeBest for
unsorted array, scanned for the minimumO(n2)O(n^2)dense graphs, m≈n2m \approx n^2
binary heap, lazy deletionO((n+m)log⁡n)O((n + m)\log n)almost everything in practice
Fibonacci heap with decrease-keyO(m+nlog⁡n)O(m + n\log n)the theoretical bound (Fredman & Tarjan, 1987)
All bounds are worst case (amortized for the Fibonacci heap). The Optimal lesson Dijkstra's Algorithm in Depth compares many more heaps and asks whether nlog⁡nn\log n is a barrier at all.
cpp
#include <cstdio>
#include <functional>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
using ll = long long;

int main() {
    int n, m, s;
    if (scanf("%d %d %d", &n, &m, &s) != 3) return 0;
    vector<vector<pair<int, ll>>> adj(n);
    for (int i = 0; i < m; i++) {
        int u, v; ll w;
        if (scanf("%d %d %lld", &u, &v, &w) != 3) return 0;
        adj[u].push_back({v, w});            // add {u, w} to adj[v] too if undirected
    }
    const ll INF = (ll)1e18;                 // never added to: only settled distances are
    vector<ll> dist(n, INF);
    priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<>> pq;  // min-heap
    dist[s] = 0;
    pq.push({0, s});
    while (!pq.empty()) {
        auto [d, u] = pq.top();
        pq.pop();
        if (d > dist[u]) continue;           // stale entry
        for (auto [v, w] : adj[u])
            if (d + w < dist[v]) {
                dist[v] = d + w;
                pq.push({dist[v], v});
            }
    }
    for (int v = 0; v < n; v++) printf("%lld\n", dist[v] == INF ? -1LL : dist[v]);
}

The contest idiom: priority_queue is a max-heap by default, and greater<> makes it a min-heap; long long distances avoid overflow; structured bindings need C++17. Input: nn, mm, the source, then mm lines "u v w" with 0-indexed vertices; unreachable vertices print −1-1. On the predict example above it prints the distances 0, 3, 1, 4, 7, 8 for S,A,B,C,D,TS, A, B, C, D, T.

Negative edges: Bellman–Ford

The proof used non-negative weights at exactly one point: the rest of a path cannot cost less than zero. Take S→AS \to A 2, S→BS \to B 4, B→AB \to A −3-3 and A→CA \to C 1. Dijkstra's algorithm settles SS (0), AA (2), CC (3) and BB (4). Relaxing B→AB \to A then lowers AA to 1, but too late: CC keeps 3, while S→B→A→CS \to B \to A \to C costs 4−3+1=24 - 3 + 1 = 2.

Bellman–Ford (Ford 1956, Bellman 1958, Moore 1959) gives up on ordering the vertices and relaxes every edge, n−1n - 1 times over. After round ii, d[v]d[v] is at most the weight of the best path to vv with at most ii edges. Without negative cycles some shortest path is simple, with at most n−1n - 1 edges, so n−1n - 1 rounds make every distance exact.

python
def bellman_ford(n, edges, s):
    """edges = [(u, v, w)]. Returns distances, or None if a negative cycle is reachable from s."""
    INF = float('inf')
    dist = [INF] * n
    dist[s] = 0
    for _ in range(n - 1):            # round i fixes every shortest path with <= i edges
        changed = False
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break                     # early exit: nothing moved this round
    if any(dist[u] + w < dist[v] for u, v, w in edges):
        return None                   # still improvable after n - 1 rounds
    return dist

O(nm)O(nm) in the worst case; the early exit helps on many inputs but not on adversarial ones. A queue-based variant that relaxes only the edges out of vertices whose distance just changed (Moore's version, called SPFA in contest circles) is often much faster in practice but keeps the O(nm)O(nm) worst case, and test data can be built to reach it.

All pairs: Floyd–Warshall

For all pairs, Dijkstra's algorithm from every vertex costs O(nmlog⁡n)O(nm\log n) with non-negative weights. On dense graphs, or with negative edges, Floyd–Warshall (Floyd 1962, building on Warshall 1962 and Roy 1959) is simpler. Number the vertices 1,…,n1, \dots, n and let D(k)[i][j]D^{(k)}[i][j] be the length of a shortest path from ii to jj whose intermediate vertices all lie in {1,…,k}\{1, \dots, k\}. Such a path either avoids kk or passes through it exactly once (without negative cycles, a repeat of kk can be cut out):

D(k)[i][j]=min⁡(D(k−1)[i][j], D(k−1)[i][k]+D(k−1)[k][j]),D(0)=WD^{(k)}[i][j] = \min\big(D^{(k-1)}[i][j],\ D^{(k-1)}[i][k] + D^{(k-1)}[k][j]\big), \qquad D^{(0)} = W
WW holds the edge weights, with 00 on the diagonal and ∞\infty for missing edges; D(n)D^{(n)} holds all the distances. A single matrix updated in place suffices, as the Optimal lesson All-Pairs Shortest Paths proves.
python
def floyd_warshall(n, edges):
    INF = float('inf')
    d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
    nxt = [[j if i == j else None for j in range(n)] for i in range(n)]
    for u, v, w in edges:
        if w < d[u][v]:
            d[u][v], nxt[u][v] = w, v
    for k in range(n):                # k outermost: allow k as an intermediate vertex
        for i in range(n):
            if d[i][k] == INF:
                continue
            for j in range(n):
                if d[i][k] + d[k][j] < d[i][j]:
                    d[i][j] = d[i][k] + d[k][j]
                    nxt[i][j] = nxt[i][k]   # first step toward j now heads toward k
    return d, nxt                     # negative cycle through i  <=>  d[i][i] < 0

def path(nxt, i, j):
    if nxt[i][j] is None:
        return []
    p = [i]
    while i != j:
        i = nxt[i][j]
        p.append(i)
    return p

O(n3)O(n^3) time and O(n2)O(n^2) memory in three tight loops: for n=500n = 500, about 1.25×1081.25 \times 10^8 simple steps, within a second in C++ by the usual rule of thumb. nxt[i][j] stores the first step of a shortest path from ii to jj, so path walks it in O(length)O(\text{length}).

Replacing (min⁡,+)(\min, +) by (or, and) turns the same triple loop into Warshall's transitive closure, r[i][j]←r[i][j]∨(r[i][k]∧r[k][j])r[i][j] \leftarrow r[i][j] \lor (r[i][k] \land r[k][j]): which vertices can reach which.

Special cases that beat the general algorithms

The general algorithms pay for their generality. When the weights or the graph have structure, simpler and faster methods apply:

WhenUseTime
all weights equalBFS: distance is the number of edgesO(n+m)O(n + m)
weights 0 or 10-1 BFS: a deque; a vertex reached by a 0-edge goes to the front, by a 1-edge to the backO(n+m)O(n + m)
small integer weights, at most CCDial's bucket queue (1969): one bucket per distance valueO(m+nC)O(m + nC)
a DAG, any weightsrelax the edges in topological orderO(n+m)O(n + m)
one target, plus a lower bound h(v)h(v) on the distance still to goA*: Dijkstra ordered by d[v]+h(v)d[v] + h(v)depends on hh; with a consistent hh, it expands no more vertices than Dijkstra, up to ties
The Artificial Intelligence course develops A* in depth. Seen from here, it is Dijkstra's algorithm on adjusted weights w(u,v)−h(u)+h(v)w(u, v) - h(u) + h(v), an idea that returns in the Optimal lesson on negative weights as Johnson's reweighting.

Why 0-1 BFS works: at every moment the deque holds vertices whose tentative distances are some value DD (toward the front) and D+1D + 1 (toward the back). Popping from the front therefore pops a minimum, exactly as Dijkstra's heap would, but without the logarithm.

Check your understanding

A grid has 10610^6 cells. Stepping into an empty cell is free, and stepping into a wall cell (destroying it) costs 1. You want the fewest walls to destroy on the way from one corner to the opposite one. Which algorithm fits best?

  1. BFS, counting the steps
  2. Bellman–Ford
  3. 0-1 BFS with a deque
  4. Floyd–Warshall
Show the answer

C. 0-1 BFS with a deque

Every move costs 0 or 1, so 0-1 BFS finds the cheapest route in O(n+m)O(n + m), a few million operations here. Dijkstra's algorithm would also be correct, with an extra logarithmic factor.

Recognizing it

Signals. "Minimum cost, time or distance", "cheapest route", "fastest way to reach every node". Then read the weights: all equal points to BFS, 0 and 1 to 0-1 BFS, non-negative to Dijkstra, negative to Bellman–Ford. Probabilities that multiply become sums under −log⁡-\log; "a loop that makes money" is a negative cycle; "all pairs" with nn up to a few hundred is Floyd–Warshall. Constraints of the form xj−xi≤cx_j - x_i \le c are shortest paths in disguise, a classic of the Optimal lesson on negative weights.

Problem (in our words)Key ideaTime
How long until a signal sent from one node reaches every node?Dijkstra from the sender; the answer is the largest distance, or "never" if some node is unreachableO((n+m)log⁡n)O((n + m)\log n)
Cheapest trip with at most kk flightsBellman–Ford for kk rounds, each relaxing from a copy of the previous round's distancesO(km)O(km)
Most reliable route, where each link succeeds with probability ppDijkstra on weights −log⁡p≥0-\log p \ge 0, or directly maximizing the productO((n+m)log⁡n)O((n + m)\log n)
Route whose single steepest climb is as small as possibleDijkstra with max⁡\max in place of ++ (or binary search on the answer with BFS)O((n+m)log⁡n)O((n + m)\log n)
The city with the fewest others within distance TT, for n≤400n \le 400Floyd–Warshall, then count per rowO(n3)O(n^3)
Each row is a classic interview or contest problem. The fourth works because max⁡\max, like ++, never decreases along a path, which is all that Dijkstra's proof needs.

Common bugs.

  • Overflow: with 32-bit integers, ∞+w\infty + w wraps around to a negative number. Use 64-bit distances, an "infinity" such as 101810^{18} that leaves headroom, and never relax out of an unreached vertex.
  • Marking a vertex done when it is pushed (the BFS habit) instead of when it is popped: its first, possibly worse, distance gets frozen.
  • Processing stale heap entries in full: still correct, but every outdated copy rescans its vertex's edges, which on adversarial inputs can make the run quadratic. Skip any entry whose key exceeds the current distance.
  • Running BFS on weighted edges, or Dijkstra's algorithm with negative ones.
  • The "at most kk edges" variant relaxed in place: with A→BA \to B 1, B→CB \to C 1, A→CA \to C 5 and k=1k = 1, the answer for CC is 5, but one in-place round (in that edge order) returns 2, a two-edge path.
  • The intermediate-vertex loop of Floyd–Warshall placed anywhere but outermost.
  • An undirected edge added in one direction only.
Check your understanding

A directed graph has n=2,000n = 2{,}000 vertices and m=10,000m = 10{,}000 edges, some of them negative, and no negative cycle. You need the distances from one source within a second. Which algorithm?

  1. Dijkstra's algorithm with a binary heap
  2. Bellman–Ford
  3. Floyd–Warshall
  4. BFS
Show the answer

B. Bellman–Ford

Bellman–Ford handles negative edges in O(nm)=2×107O(nm) = 2 \times 10^7 relaxations, comfortably fast. Floyd–Warshall would also be correct, but it takes n3=8×109n^3 = 8 \times 10^9 steps and computes all pairs, which nobody asked for.

Key takeaways

  • All three algorithms only relax edges: d[v]←min⁡(d[v],d[u]+w(u,v))d[v] \leftarrow \min(d[v], d[u] + w(u, v)). Distances are exact once no edge can be relaxed, and parent pointers form a shortest-path tree.
  • Dijkstra's algorithm settles vertices in order of distance and needs non-negative weights; with a binary heap and lazy deletion it runs in O((n+m)log⁡n)O((n + m)\log n).
  • Bellman–Ford relaxes every edge n−1n - 1 times, O(nm)O(nm), handles negative edges, and detects a reachable negative cycle with one more round.
  • Floyd–Warshall computes all pairs in O(n3)O(n^3) by allowing intermediate vertices one at a time; the loop over the intermediate vertex must be outermost.
  • BFS (equal weights), 0-1 BFS (weights 0 or 1) and relaxation in topological order (DAGs) beat the general algorithms when they apply.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the lazy-deletion version of Dijkstra's algorithm, a popped entry (d,u)(d, u) has d>dist[u]d > \text{dist}[u]. Why is it safe to skip it?

  1. It is an outdated copy: uu was already settled with the smaller value dist[u]\text{dist}[u], and its edges were relaxed then
  2. It signals a negative cycle through uu
  3. It means uu cannot be reached from the source
  4. Skipping it is required for correctness: processing it would produce wrong distances
Show the answer

A. It is an outdated copy: uu was already settled with the smaller value dist[u]\text{dist}[u], and its edges were relaxed then

Each improvement of dist[u]\text{dist}[u] pushed a new entry, so older entries with larger keys stay in the heap. The entry with the final value was popped first and relaxed uu's edges. Processing a stale copy would only redo work, which on adversarial inputs can add up.

Question 2

Why does Bellman–Ford need only n−1n - 1 rounds when there is no negative cycle?

  1. Each round settles the vertex closest to the source, as in Dijkstra's algorithm
  2. Some shortest path to each vertex is simple, so it has at most n−1n - 1 edges, and round ii makes every path of at most ii edges count
  3. The distances shrink by at least 1 per round, so n−1n - 1 rounds exhaust them
  4. Each round relaxes n−1n - 1 edges
Show the answer

B. Some shortest path to each vertex is simple, so it has at most n−1n - 1 edges, and round ii makes every path of at most ii edges count

After round ii, d[v]d[v] is at most the weight of the best path to vv with at most ii edges. Without negative cycles, cutting a cycle out of a path never makes it more expensive, so a simple shortest path exists, with at most n−1n - 1 edges.

Question 3

After Floyd–Warshall, the diagonal entry d[i][i]d[i][i] is negative. What does that mean?

  1. An edge leaving ii has negative weight
  2. ii cannot reach itself
  3. ii lies on a negative cycle
  4. An integer overflow occurred at ii
Show the answer

C. ii lies on a negative cycle

d[i][i]d[i][i] starts at 00 and only decreases when some path from ii back to ii is negative, which is a negative cycle through ii. Distances between vertices that can reach such a cycle and be reached from it are then meaningless.

Question 4

An undirected graph has one edge of weight −1-1 and all other weights positive. You run Bellman–Ford with each edge replaced by two opposite arcs, and it reports a negative cycle. Why?

  1. Bellman–Ford cannot handle any negative weight
  2. The edge {u,v}\{u, v\} became the arcs u→vu \to v and v→uv \to u, a cycle of weight −2-2
  3. Undirected graphs always contain cycles
  4. The report is a bug: undirected graphs cannot have negative cycles
Show the answer

B. The edge {u,v}\{u, v\} became the arcs u→vu \to v and v→uv \to u, a cycle of weight −2-2

The two arcs of one undirected edge form a 2-cycle whose weight is twice the edge's. With a negative edge, that round trip is a genuine negative cycle in the directed version, so "shortest walks" really are unbounded.

Go deeper

Further reading

  • E. W. Dijkstra, "A note on two problems in connexion with graphs," Numerische Mathematik 1 (1959), 269–271.
  • R. Bellman, "On a routing problem," Quarterly of Applied Mathematics 16(1) (1958), 87–90.
  • R. W. Floyd, "Algorithm 97: Shortest path," Communications of the ACM 5(6) (1962), 345.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 22 and 23.