Sub topic 14
Choosing an Algorithm: Bellman-Ford, Floyd-Warshall, or Dijkstra
This chapter assumes you know Big-O notation, can read Python, and have worked through the earlier chapters on Bellman-Ford and Floyd-Warshall. Knowing Dijkstra's algorithm helps but is not required. The goal is to pick the right shortest-path algorithm from four facts about the problem:
- the number of vertices V
- the number of edges E
- whether any edge weight is negative
- whether you need distances from one source or between all pairs
The Cost Table
The table below lists the standard costs. Dijkstra is shown with a binary heap, which is what Python's heapq gives you.
| Algorithm | Problem solved | Negative edges | Time | Extra space |
|---|---|---|---|---|
| Dijkstra (binary heap) | Single-source | No | O((V + E) log V) | O(V) |
| Bellman-Ford | Single-source | Yes, detects reachable negative cycles | O(VE), O(E) best case with early exit | O(V) |
| Floyd-Warshall | All-pairs | Yes, detects any negative cycle | O(V³) | O(V²) |
| Dijkstra from every vertex | All-pairs | No | O(V(V + E) log V) | O(V²) for output |
| Bellman-Ford from every vertex | All-pairs | Yes | O(V²E) | O(V²) for output |
| Johnson's algorithm | All-pairs | Yes | O(VE log V) | O(V²) for output |
Two observations from the table do most of the work.
First, the density of the graph changes the picture. A sparse graph has E close to V. A dense graph has E close to V². Bellman-Ford's O(VE) is about O(V²) on sparse graphs and about O(V³) on dense ones.
Second, running Bellman-Ford from every vertex is almost never the right choice. On a dense graph it costs O(V⁴), which is a factor of V worse than Floyd-Warshall.
Putting Numbers on It
Asymptotic notation hides constants, so it helps to plug in sizes. The counts below are rough numbers of basic operations.
| Scenario | V | E | Floyd-Warshall (V³) | Bellman-Ford, one source (VE) | Dijkstra, one source ((V+E) log V) |
|---|---|---|---|---|---|
| Road network fragment | 1,000 | 5,000 | 1 × 10⁹ | 5 × 10⁶ | about 6 × 10⁴ |
| Dense graph | 1,000 | 1,000,000 | 1 × 10⁹ | 1 × 10⁹ | about 1 × 10⁷ |
| Small dense graph | 200 | 40,000 | 8 × 10⁶ | 8 × 10⁶ | about 3 × 10⁵ |
Pure Python does roughly 10⁷ simple loop steps per second. So 10⁹ operations take minutes in Python and about a second in C or with vectorized NumPy. At V = 1,000, Floyd-Warshall is fine in a compiled language and slow in plain Python.
Memory sets a hard ceiling on Floyd-Warshall. The distance matrix has V² entries. At V = 10,000 that is 10⁸ entries, which is 800 MB as 64-bit floats in NumPy and several times more as nested Python lists. The next-hop matrix doubles it. Bellman-Ford keeps only O(V) state besides the edge list, so it scales to graphs with millions of vertices.
Why Constants Favor Floyd-Warshall on Small Graphs
Floyd-Warshall's inner loop is three nested for loops over arrays, with no heap and no adjacency-list pointer chasing. That loop has good cache locality and vectorizes well. Dijkstra pays for heap operations and scattered memory access on every edge. On small dense graphs, often up to a few hundred vertices, Floyd-Warshall frequently beats V runs of Dijkstra in practice, even where the Big-O comparison is close. Floyd-Warshall is also about fifteen lines of code with few places for bugs, and that matters when the graph is small enough that speed does not.
A Decision Procedure
The function below encodes the same logic. It compares estimated operation counts, so it shows the crossover points directly instead of using fixed thresholds.
import math
def choose_algorithm(n, m, has_negative_edges, all_pairs):
"""Return the name of a suitable shortest-path algorithm.
n: number of vertices, m: number of edges.
Costs are rough operation counts that ignore constant factors.
"""
log_n = math.log2(max(n, 2))
if not all_pairs:
return "Bellman-Ford" if has_negative_edges else "Dijkstra"
floyd_cost = n ** 3
repeated_dijkstra = n * (n + m) * log_n
if has_negative_edges:
# Johnson: one Bellman-Ford pass to reweight, then n Dijkstra runs
sparse_cost = n * m + repeated_dijkstra
sparse_name = "Johnson"
else:
sparse_cost = repeated_dijkstra
sparse_name = "Dijkstra from every vertex"
return "Floyd-Warshall" if floyd_cost <= sparse_cost else sparse_name
print(choose_algorithm(1000, 5000, False, False)) # Dijkstra
print(choose_algorithm(1000, 5000, True, False)) # Bellman-Ford
print(choose_algorithm(1000, 5000, True, True)) # Johnson
print(choose_algorithm(300, 80000, True, True)) # Floyd-WarshallHere are the last two cases worked out. With V = 1,000 and E = 5,000, Floyd-Warshall costs 10⁹. Johnson costs about 5 × 10⁶ + 1,000 × 6,000 × 10 ≈ 6.5 × 10⁷, so Johnson wins by a factor of about 15. With V = 300 and E = 80,000 the graph is nearly complete. Floyd-Warshall costs 2.7 × 10⁷, and Johnson costs about 2.2 × 10⁸, so Floyd-Warshall wins.
Query Patterns Change the Answer
The single-source versus all-pairs choice depends on how many sources you will query, not only on how the problem is worded.
- A few sources, known in advance. Run the single-source algorithm k times. Bellman-Ford k times costs O(kVE). That beats Floyd-Warshall when kE < V², which holds for small k on sparse graphs.
- Many arbitrary queries on a fixed graph. Precompute all pairs once, then answer each query in O(1) with a table lookup.
- The graph changes between queries. Recomputing Floyd-Warshall costs O(V³) per change. Running a single-source algorithm on demand is often cheaper.
- Only reachability is needed. Use the Boolean variant of Floyd-Warshall (transitive closure), or a BFS from each vertex on sparse graphs.
Failure Modes When You Pick Wrong
Dijkstra on negative edges gives wrong answers silently
Dijkstra finalizes a vertex as soon as it leaves the heap. A negative edge found later could still lower that vertex's distance, but Dijkstra never looks at it again. No exception is raised, and the output just contains wrong distances. If negative weights are possible, check for them at the trust boundary:
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
if any(w < 0 for _, _, w in edges):
print("negative weight present: Dijkstra is unsafe")Undirected graphs with a negative edge
An undirected edge {u, v} with weight -2 becomes two directed edges, u→v and v→u, each weighing -2. Together they form a cycle of weight -4. Any undirected graph with a negative edge therefore has a negative cycle, and neither Bellman-Ford nor Floyd-Warshall can return meaningful distances for it. That problem needs different techniques, such as matching-based methods. These algorithms do not handle it.
Detection scope differs
Bellman-Ford reports only negative cycles that are reachable from its source. Floyd-Warshall reports any negative cycle in the graph through the diagonal. To check a whole graph with Bellman-Ford, add a virtual source with zero-weight edges to every vertex, as Johnson's algorithm does.
Numeric blow-up in Floyd-Warshall
If a negative cycle exists, Floyd-Warshall keeps running, and some entries can grow negative very quickly, roughly doubling in magnitude with each k. Python floats tolerate this. Fixed-width integers in C or NumPy can overflow and wrap around to positive values, and that can hide the negative diagonal entries. In those languages, check the diagonal after each k, or clamp the values.
Summary of Selection Rules
| Situation | Choose |
|---|---|
| One source, non-negative weights | Dijkstra |
| One source, negative weights possible | Bellman-Ford |
| All pairs, V up to a few hundred, or dense | Floyd-Warshall |
| All pairs, large sparse, non-negative | Dijkstra from every vertex |
| All pairs, large sparse, negative weights | Johnson's algorithm |
| Need to detect a negative cycle anywhere | Floyd-Warshall (small V) or Bellman-Ford with a virtual source |
Exercise
A graph has V = 5,000 vertices and E = 20,000 edges, some with negative weights. You need distances between all pairs. Estimate the cost of Floyd-Warshall and of Johnson's algorithm, check whether Floyd-Warshall's distance matrix fits in 1 GB as 64-bit floats, and choose.
Show answer
Floyd-Warshall costs 5,000³ = 1.25 × 10¹¹ operations. Johnson costs about VE + V(V+E) log V = 10⁸ + 5,000 × 25,000 × 12.3 ≈ 1.6 × 10⁹, which is roughly 80 times less. The distance matrix holds 2.5 × 10⁷ entries × 8 bytes = 200 MB, so it fits, but the time cost still makes Johnson the better choice.
Exercise
You must answer shortest-path queries from 3 fixed sources on a graph with V = 2,000, E = 10,000, and some negative weights. Should you use Floyd-Warshall or Bellman-Ford?
Show answer
Run Bellman-Ford three times. That costs about 3 × 2,000 × 10,000 = 6 × 10⁷ operations, and early exit often makes it less. Floyd-Warshall costs 8 × 10⁹ operations and needs a 4-million-entry matrix, most of which you would never read.
Exercise
A colleague runs Dijkstra on an undirected graph that has one edge of weight -1, and the program returns distances without an error. Explain why those distances are not trustworthy, and say what Bellman-Ford would report.
Show answer
The undirected edge becomes two directed edges that form a cycle of weight -2, so shortest paths are undefined for every vertex that can reach that cycle. Dijkstra finalizes vertices early and never detects this, so it prints wrong numbers without any error. Bellman-Ford's extra pass would still find a relaxable edge and report a negative cycle, as long as the edge is reachable from the source.