Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Shortest paths: Dijkstra, Bellman–Ford, A* and Floyd–Warshall

ProblemFind the cheapest path from a source to every vertex, or to one target, or between every pair of vertices, in a weighted graph
Devised byEdsger Dijkstra (1959); Richard Bellman (1958), Lester Ford (1956) and Edward Moore (1959); Peter Hart, Nils Nilsson and Bertram Raphael (1968), A*; Robert Floyd (1962) and Stephen Warshall (1962)
AccuracyExact; distances agree with SciPy’s csgraph to the last digit (see the chapter overview)
CostDijkstra ; Bellman–Ford , often far less with early exit; A* at most Dijkstra’s, usually much less; Floyd–Warshall time and memory
Read firstGraphs, traversal and orderings
APIdijkstra, bellman_ford, a_star, ShortestPaths (distance, predecessor, path_to), floyd_warshall, AllPairsShortestPaths (distance, path)

Overview

The length of a path is the sum of its edge weights, and a shortest path minimises it. Every algorithm here rests on relaxation: if reaching costs and the edge costs , then costs at most . Dijkstra’s algorithm settles vertices in order of distance, which is correct when no weight is negative. Bellman–Ford relaxes every edge repeatedly, which handles negative weights and detects negative cycles. A* is Dijkstra steered toward a single target by an estimate of the remaining distance. Floyd–Warshall finds all pairs at once by allowing paths through one more intermediate vertex at each stage. Each returns predecessors, so the paths themselves can be reconstructed.

Where it is used

Shortest paths are among the most-run algorithms in the world.

  • Navigation. Route planners in cars and phones run Dijkstra-type and A* searches on road graphs with travel times as weights.
  • Internet routing. OSPF and IS-IS routers run Dijkstra to build routing tables; RIP uses Bellman-Ford.
  • Robotics and games. A* finds a collision-free path across a grid or navigation mesh.
  • Finance and logistics. Negative-cycle detection by Bellman-Ford finds arbitrage; Floyd-Warshall computes all-pairs distances in small networks.

History

Lester Ford (1956), Richard Bellman (1958) and Edward Moore (1959) found the repeated-relaxation algorithm independently, in the context of network flows, dynamic programming and maze routing. Edsger Dijkstra devised his algorithm in 1956, in twenty minutes at a café in Amsterdam, to demonstrate the ARMAC computer. He published it in 1959; the heap-based version is due to later work, and Michael Fredman and Robert Tarjan’s Fibonacci heap (1984) gave its best bound. Peter Hart, Nils Nilsson and Bertram Raphael (1968) developed A* for the Shakey robot’s path planning. Robert Floyd and Stephen Warshall (both 1962) published the all-pairs dynamic programme. Bernard Roy had found it in 1959.

The idea

Dijkstra

All four algorithms share one operation. Each vertex has a tentative distance , the length of the best path to it found so far (infinite at the start, 0 for the source). To relax an edge of weight is to ask whether going through improves on that: if , set and record as the predecessor of . The algorithms differ in the order in which they relax edges.

Dijkstra’s algorithm processes the vertices in order of their distance from the source, like a wave spreading outwards.

  1. Among the vertices not yet finished, pick the one with the smallest tentative distance. Call it , and declare it settled: its tentative distance is final.
  2. Relax every edge leaving .
  3. Repeat until every vertex is settled (or the target is).

Why step 1 is safe. Suppose has the smallest tentative distance among the unsettled vertices. Any other route to must leave the settled set at some point, through some other unsettled vertex , and already. If no edge has negative weight, the rest of that route can only add to its length, so it cannot be shorter than . Hence is the true distance. The argument fails with negative weights, and so does the algorithm.

The vertex of smallest tentative distance is supplied by a binary heap, which makes the cost . When a vertex’s distance improves, a new entry is pushed and the old one is left in the heap; such stale entries are skipped when they are popped.

Bellman–Ford

When some weights are negative (a cost that can also be a gain, such as a currency exchange), Dijkstra’s greedy choice is no longer valid. Bellman-Ford makes no such choice. It simply relaxes every edge, and repeats.

The reason this works: a shortest path never needs to visit a vertex twice, so it has at most edges. After the first pass over all the edges, every vertex whose shortest path has one edge has its correct distance. After the second pass, so does every vertex whose shortest path has two edges, and so on. After passes all the distances are correct, at a cost of .

The one exception is a reachable negative cycle, a loop whose weights sum to less than zero. Going round it again always lowers the cost, so no shortest path exists. Such a cycle betrays itself: if a -th pass still improves some distance, there must be one, and the library returns an error. It also stops early as soon as a pass changes nothing, which on typical graphs takes a few passes, not . In undirected graphs a negative edge is itself a negative cycle, walked back and forth.

A*

Dijkstra’s wave spreads equally in all directions, although we may want the path to just one target. A* aims the search. It needs a heuristic , an estimate of the remaining cost from to the target, and it orders the heap by : the cost so far plus the estimated cost to go. Vertices that lie in the direction of the target are tried first.

The result is still guaranteed optimal under two conditions on . It must never overestimate the true remaining cost (it is admissible), and it must satisfy for every edge (it is consistent), which says that the estimate cannot drop by more than the cost of the step taken. Then the first time the target is popped from the heap, its path is optimal. Straight-line distance on a map and Manhattan distance on a grid are consistent heuristics, since no path can be shorter than the direct one. Good heuristics explore far fewer vertices than Dijkstra; is Dijkstra itself.

Figure 23.1. Grid paths.

Dijkstra’s distance to the target is 156, A*’s path costs 156 over 156 steps. Dijkstra settled the whole grid in 0.12 ms; A* with the Manhattan heuristic stopped at the target after 0.12 ms. In this maze the walls force a long detour, so the heuristic saves little.

Floyd–Warshall

To find the shortest paths between all pairs of vertices, Floyd-Warshall uses dynamic programming over a cleverly chosen family of subproblems: restrict which vertices a path may pass through. Let be the shortest distance from to using only the vertices as intermediate stops. With no stops are allowed, and is just the weight of the edge from to . Now allow vertex as well. The best path either does not use , or goes from to and then from to , each part using only earlier vertices:

After all vertices have been allowed, the matrix holds the true distances. The update can be done in place in a single matrix, with three nested loops, for a cost of . A successor matrix records the first step of each path, from which the paths can be read off. Negative weights are allowed, and a negative diagonal entry at the end reveals a negative cycle.

Figure 23.2. Shortest path timings.

Floyd–Warshall’s cubic cost limits it to graphs of a few thousand vertices. For all pairs on sparse graphs, running Dijkstra from every source is cheaper.

Algorithm

Dijkstra from a source.

  1. Set every distance to infinity, except the source’s, which is 0. Push (0, source) on a min-heap ordered by distance.
  2. Pop the entry (d, u) of smallest distance. If is larger than the distance now recorded for , the entry is stale: discard it and repeat this step.
  3. For each edge from to with weight : if is less than the recorded distance of , record it, set the predecessor of to , and push .
  4. Repeat from step 2 until the heap is empty.

With a binary heap the cost is .

Bellman-Ford from a source.

  1. Set the distances as above.
  2. Make a pass over all the edges (in both directions, for an undirected graph), relaxing each.
  3. If the pass changed nothing, stop: the distances are final.
  4. After passes, make one more. If it would still improve some distance, report a negative cycle.

The cost is in the worst case.

A* from a source to a target, with a heuristic : as Dijkstra, with these differences. The heap is ordered by . A vertex is closed when it is popped, and closed vertices are not reopened. The search stops as soon as the target is popped.

Floyd-Warshall for all pairs.

  1. Initialise the matrix: 0 on the diagonal, the weight for each edge, infinity elsewhere. Initialise the successor matrix to the edge’s endpoint.
  2. For each , and for each pair : if , replace by the sum, and the successor of by the successor of . The loop over must be the outermost.
  3. If any diagonal entry is negative, report a negative cycle.

The cost is time and memory.

Recovering a path: from the predecessors, walk back from the target to the source and reverse the list; from the successor matrix, walk forward from the source.

Implementation

    while let Some(State { cost, vertex }) = heap.pop() {
        if cost > distance[vertex] {
            continue;
        }
        for &(next, w) in g.neighbors(vertex) {
            let candidate = cost + w;
            if candidate < distance[next] {
                distance[next] = candidate;
                predecessor[next] = Some(vertex);
                heap.push(State { cost: candidate, vertex: next });
            }
        }
    }
    for k in 0..n {
        for i in 0..n {
            let dik = distance[i][k];
            if !dik.is_finite() {
                continue;
            }
            for j in 0..n {
                let candidate = dik + distance[k][j];
                if candidate < distance[i][j] {
                    distance[i][j] = candidate;
                    next[i][j] = next[i][k];
                }
            }
        }
    }
  • dijkstra and a_star reject negative weights; unreachable vertices have distance f64::INFINITY.
  • ShortestPaths::path_to follows predecessors back to the source.

In practice

//! Single-source and all-pairs shortest paths.

use lib_jsl_graph::{Graph, a_star, bellman_ford, dijkstra, floyd_warshall};

fn main() {
    // Road distances between five towns.
    let roads = [(0, 1, 7.0), (0, 2, 9.0), (0, 5, 14.0), (1, 2, 10.0), (1, 3, 15.0), (2, 3, 11.0), (2, 5, 2.0), (3, 4, 6.0), (4, 5, 9.0)];
    let g = Graph::from_edges(6, &roads, false).unwrap();
    let d = dijkstra(&g, 0).unwrap();
    println!("Dijkstra from 0: {:?}", d.distance);
    println!("path to 4: {:?}", d.path_to(4).unwrap());
    // A* with a zero heuristic is Dijkstra stopped at the target.
    println!("A* to 4: {:?}", a_star(&g, 0, 4, |_| 0.0).unwrap());
    // Negative arcs (but no negative cycle): Bellman-Ford.
    let signed = Graph::from_edges(4, &[(0, 1, 4.0), (0, 2, 5.0), (1, 3, 3.0), (2, 1, -3.0), (2, 3, 4.0)], true).unwrap();
    let b = bellman_ford(&signed, 0).unwrap();
    println!("Bellman-Ford: {:?}, path to 3 {:?}", b.distance, b.path_to(3).unwrap());
    let cycle = Graph::from_edges(3, &[(0, 1, 1.0), (1, 2, -2.0), (2, 1, 1.0)], true).unwrap();
    println!("with a negative cycle: {:?}", bellman_ford(&cycle, 0).map(|_| ()));
    let all = floyd_warshall(&g).unwrap();
    println!("Floyd-Warshall: 3 → 0 costs {}, via {:?}", all.distance[3][0], all.path(3, 0).unwrap());
}
Dijkstra from 0: [0.0, 7.0, 9.0, 20.0, 20.0, 11.0]
path to 4: [0, 2, 5, 4]
A* to 4: Some((20.0, [0, 2, 5, 4]))
Bellman-Ford: [0.0, 2.0, 5.0, 5.0], path to 3 [0, 2, 1, 3]
with a negative cycle: Err(RuntimeError("A negative cycle is reachable from the source."))
Floyd-Warshall: 3 → 0 costs 20, via [3, 2, 0]

Strengths

  • The standard algorithms with path reconstruction, negative-weight support and negative-cycle detection.
  • A* accepts any heuristic as a closure.

Weaknesses

  • A* closes vertices, so an admissible but inconsistent heuristic can return a suboptimal path.
  • No bidirectional search, contraction hierarchies or other speed-ups for very large road networks.

Exercises

  1. Show that Dijkstra’s algorithm fails with a negative edge, using a three-vertex example.
  2. Prove that Bellman–Ford passes suffice without negative cycles.
  3. Show that a consistent heuristic is admissible, and that A* with it never reopens a vertex.
  4. Prove the Floyd–Warshall recurrence, and explain why updating in place is safe.
  5. Use Johnson’s reweighting , with from one Bellman–Ford run, to apply Dijkstra to a graph with negative edges.
Hints and answers
  1. Take edges of weight 2, of weight 3 and of weight . Dijkstra fixes at distance 2 (smaller than 3) but the path has weight 1.
  2. A shortest path without negative cycles has at most edges, and pass makes all shortest paths with at most edges correct (induction on ), so passes suffice.
  3. Consistency, with , gives by induction along a path the true distance to the goal: admissible. With a consistent the values along a path never decrease, so the first time a vertex is popped its is final and it is never reopened.
  4. , where allows intermediate vertices . In-place updating is safe because and do not change in iteration (the diagonal entry ).
  5. For any path from to the reweighting adds , which depends only on the endpoints, so shortest paths stay shortest. With the Bellman-Ford distances from a virtual source, for every edge, so Dijkstra applies; add to recover true distances.

Further reading

  • E. W. Dijkstra, “A note on two problems in connexion with graphs”, Numerische Mathematik 1 (1959) 269–271.
  • P. E. Hart, N. J. Nilsson and B. Raphael, “A formal basis for the heuristic determination of minimum cost paths”, IEEE Transactions on Systems Science and Cybernetics 4 (1968) 100–107.
  • R. W. Floyd, “Algorithm 97: Shortest path”, Communications of the ACM 5 (1962) 345.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022, chapters 22–23.