When edge weights can be negative, Dijkstra's greedy assumption collapses. Bellman-Ford fixes this by brute patience: it relaxes every edge V - 1 times, runs in O(V · E), and can detect negative cycles. Floyd-Warshall solves the all-pairs problem with a three-line dynamic program in O(V³). Together with BFS and Dijkstra, they complete the shortest-path toolkit, and knowing which one to pick is a classic interview question.
Think of it like
Planning trips with layovers
Bellman-Ford is a travel agent who, each round, allows one more flight per trip: after round 1 she knows the best nonstop fares, after round 2 the best one-stop fares, and so on. No sensible trip needs more than V - 1 flights. Floyd-Warshall is an agent who instead allows one more hub airport at a time: first trips may connect only through Atlanta, then through Atlanta or Chicago, until every airport is allowed as a hub. A negative cycle is a loop of flights with rebates so generous that flying it forever makes you richer.
Why negative edges need something else
Negative weights appear whenever an edge represents a gain rather than a cost: rebates, energy recovered going downhill, profit in a trade, or the -log of an exchange rate. Dijkstra's Algorithm settles a vertex once and never revisits it, which is only safe if later edges cannot make a path shorter. With negative edges they can.
Bellman-Ford
Bellman-Ford keeps the familiar dist array and relaxes every edge in rounds. It needs nothing but an edge list, which makes it one of the simplest graph algorithms to implement correctly.
- 1
Initialize
dist[s] = 0, everything else infinity. - 2
Relax every edge
For each edge
(u, v, w): ifdist[u]is finite anddist[u] + w < dist[v], lowerdist[v](and recordparent[v] = u). - 3
Repeat V - 1 rounds
Stop early if a full round changes nothing.
- 4
Run one more round
If any edge can still be relaxed, a negative cycle is reachable from
s.
Why V - 1 rounds?
Without negative cycles, some shortest path to each vertex is simple, so it has at most V - 1 edges. Bellman-Ford maintains the invariant below. The i-th edge of a shortest path gets relaxed in round i at the latest, no matter what order the edges are scanned in, because by then its tail already has its correct distance.
Here is a run from S with edges processed in a deliberately unlucky order: A→C 3, B→A -2, S→B 4, S→A 5. Information travels only one edge per round when edges are scanned "backwards" like this, which is exactly the worst case the V - 1 bound protects against.
| Round | Changes | dist (S, A, B, C) |
|---|---|---|
| Start | none | 0, ∞, ∞, ∞ |
| 1 | S→B sets B = 4; S→A sets A = 5 | 0, 5, 4, ∞ |
| 2 | A→C sets C = 8; B→A improves A to 2 | 0, 2, 4, 8 |
| 3 | A→C improves C to 5 | 0, 2, 4, 5 |
| 4 (check) | nothing relaxes: no negative cycle | 0, 2, 4, 5 |
Detecting and finding negative cycles
After V - 1 rounds every finite distance is final unless a negative cycle interferes. So if round V still relaxes some edge u → v, a negative cycle is reachable from the source. To extract the cycle, take the vertex x relaxed in round V, follow parent pointers V times (this guarantees you land on the cycle itself), then keep following parents until you return to the same vertex.
- Any negative cycle anywhere, not just reachable from
s: start withdist = 0for every vertex (a virtual source connected to all vertices). - Which vertices have distance minus infinity: mark every vertex relaxed in round
V, then BFS or DFS from those marks. Everything reached is affected (CSES High Score uses this). - Longest paths with positive cycles: negate every weight and look for negative cycles on the route that matters.
Hop-limited shortest paths
Bellman-Ford's rounds have a precise meaning: after round i, paths of at most i edges are covered. That makes it a natural fit for "at most k stops" (that is, k + 1 edges). The catch: within one round, an update to dist[u] can be reused immediately by a later edge out of u, sneaking in extra edges. Relax from a copy of the previous round's distances.
def find_cheapest_price(n, flights, src, dst, k):
INF = float("inf")
dist = [INF] * n
dist[src] = 0
for _ in range(k + 1): # k stops = at most k + 1 edges
prev = dist[:] # relax only from LAST round's values
for u, v, w in flights:
if prev[u] != INF and prev[u] + w < dist[v]:
dist[v] = prev[u] + w
return dist[dst] if dist[dst] != INF else -1SPFA: the queue-based variant
The Shortest Path Faster Algorithm only relaxes edges out of vertices whose distance just changed, keeping those vertices in a FIFO queue. On random graphs it is often far faster than plain Bellman-Ford, but its worst case is still O(V · E) and adversarial inputs (common in programming contests) trigger it. To detect negative cycles, count how many edges each vertex's current path uses; reaching V means a cycle.
Floyd-Warshall
Floyd-Warshall computes shortest paths between all pairs of vertices. It is a dynamic program over the set of vertices allowed as intermediate stops. Let d_k[i][j] be the shortest i → j distance using only vertices 0..k in between. The best such path either avoids k entirely, or passes through k exactly once and splits into two halves that only use 0..k-1.
for k in range(n): # allow vertex k as an intermediate stop
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]- Path reconstruction: keep
next[i][j], the first hop on the besti → jpath. Initialize it tojfor each edge; when going throughkimproves the pair, setnext[i][j] = next[i][k]. Walki, next[i][j], …until you reachj. - Negative cycles: after the run,
dist[i][i] < 0for someimeans a negative cycle exists. Any pair(i, j)with aksuch thatdist[i][k]anddist[k][j]are finite anddist[k][k] < 0has no shortest path. - Memory:
O(V²)for the matrix.Vup to a few hundred (around 500) is comfortable;V = 1000means 10⁹ inner iterations, which is slow in most languages.
Transitive closure
Replace min and + with or and and and you get Warshall's algorithm: reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j]). It answers "can i reach j?" for every pair in O(V³), or roughly O(V³ / 64) when each row is stored as a bitset. Course Schedule IV is exactly this problem.
Choosing a shortest-path algorithm
| Algorithm | Weights | Question answered | Time | Notes |
|---|---|---|---|---|
| Breadth-First Search | Unweighted | Single source | O(V + E) | Fewest edges |
| 0-1 BFS | 0 or 1 | Single source | O(V + E) | Deque instead of heap |
| DAG relaxation | Any, but no cycles | Single source | O(V + E) | Relax in Topological Sort order |
| Dijkstra's Algorithm | Non-negative | Single source | O((V + E) log V) | Greedy with a priority queue |
| Bellman-Ford | Any | Single source | O(V · E) | Detects negative cycles |
| Floyd-Warshall | Any (no negative cycles) | All pairs | O(V³) | Simple; best for small or dense graphs |
| Johnson's | Any (no negative cycles) | All pairs | O(V · E log V) | Bellman-Ford once, then V Dijkstras |
| A* Pathfinding | Non-negative + heuristic | Single pair | O((V + E) log V) worst case | Explores far less with a good heuristic |
Applications
Currency arbitrage is the textbook use of negative-cycle detection. A sequence of trades is profitable when the product of exchange rates exceeds 1. Taking -log turns products into sums and "greater than 1" into "less than 0".
- Distance-vector routing: RIP and the original ARPANET routing ran a distributed Bellman-Ford, each router relaxing with its neighbors' tables (and suffering the famous count-to-infinity problem).
- Difference constraints: a system of inequalities
x_j - x_i ≤ cbecomes edgesi → jwith weightc; it is feasible iff there is no negative cycle, and Bellman-Ford distances give a solution. Used in scheduling and timing analysis. - All-pairs tables: distance matrices for small road networks, game maps or network latency, computed once with Floyd-Warshall.
- Reachability queries: transitive closure in databases, type systems and access-control graphs.
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Bellman-Ford | O(V · E) | O(V) | Best case O(E) with early termination |
| Negative-cycle check | O(V · E) | O(V) | One extra round after V - 1 |
| SPFA | O(V · E) | O(V) | Worst case; often much faster in practice |
| Floyd-Warshall | O(V³) | O(V²) | All pairs; in-place DP |
| Transitive closure (Warshall) | O(V³) | O(V²) | About V³/64 word operations with bitsets |
| Johnson's algorithm | O(V · E log V) | O(V²) | Sparse all-pairs with negative edges |
Johnson's bound assumes a connected graph (E ≥ V - 1) and binary-heap Dijkstra; the O(V²) space is for storing all pairwise distances.
Implementation
`edges` holds `(u, v, w)` triples; weights may be negative. Returns the distance array, or nothing if a negative cycle is reachable from the source.
def bellman_ford(n: int, edges: list[tuple[int, int, int]], source: int) -> list[float] | None:
INF = float("inf")
dist = [INF] * n
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]: # skip unreached tails
dist[v] = dist[u] + w
changed = True
if not changed:
break # early exit: distances are final
for u, v, w in edges: # round V: any improvement = negative cycle
if dist[u] != INF and dist[u] + w < dist[v]:
return None
return dist
# The worked example: S, A, B, C = 0, 1, 2, 3
print(bellman_ford(4, [(1, 3, 3), (2, 1, -2), (0, 2, 4), (0, 1, 5)], 0)) # [0, 2, 4, 5]Key takeaways
- Bellman-Ford relaxes every edge
V - 1times because a shortest simple path has at mostV - 1edges; it costsO(V · E). - If round
Vstill relaxes an edge, a negative cycle is reachable from the source; follow parents to extract it. - Copy the previous round's distances when you need paths with at most
kedges. - Floyd-Warshall is a DP over allowed intermediate vertices:
O(V³)time,O(V²)space, andkmust be the outer loop. - Choose by assumptions: BFS (unweighted), Dijkstra (non-negative), Bellman-Ford (negative, single source), Floyd-Warshall or Johnson (all pairs).
Common pitfalls
- Relaxing from an unreached vertex: in fixed-width integers
INF + (negative w)looks smaller thanINFand corrupts distances. - Putting
kin the inner loop of Floyd-Warshall. - Treating a negative cycle anywhere in the graph as affecting the source, or missing one that is not reachable from it, without thinking about which one the problem asks for.
- Updating
distin place during a round of a hop-limited search, letting one round use several edges. - Integer overflow when adding two large distances in Java or C++; use 64-bit values and a sentinel like
Long.MAX_VALUE / 4.
Interview tips
- Justify the
V - 1bound in one sentence: a shortest simple path visits each vertex at most once. - For "at most k stops", offer Bellman-Ford with
k + 1rounds on a copied array; it is shorter and safer than a modified Dijkstra. - When
nis small (up to about 400) and you need many distance queries, Floyd-Warshall is often the simplest correct answer.
Real-world applications
- Arbitrage detection in currency and crypto markets (negative cycles under −log weights).
- Distance-vector routing protocols such as RIP.
- Solving systems of difference constraints in scheduling and circuit timing.
- Precomputing all-pairs distance tables for small networks and game maps.
- Transitive closure for reachability queries in databases and dependency graphs.
Practice problems
Test yourself
Why does Bellman-Ford run exactly V - 1 rounds of relaxation?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.