Sub topic 2
Why V-1 Rounds Are Enough
This chapter assumes you know how edge relaxation works and have seen the basic Bellman-Ford loop. It explains why that loop is correct, then introduces Floyd-Warshall.
Why V-1 Rounds Are Enough
Suppose the graph has no negative cycle reachable from the source. Then every shortest path can be taken to be simple, meaning it repeats no vertex. A simple path visits at most V vertices, so it has at most V-1 edges.
After round i, every vertex whose shortest path uses at most i edges has its correct distance. This holds by induction. Round i relaxes the last edge of each such path, and the vertex before that edge was already correct after round i-1. After V-1 rounds, every vertex is correct.
Detecting Negative Cycles with One More Pass
Run one extra pass over all edges. If any edge still satisfies dist[u] + w < dist[v], the distances have not settled. That can only happen when a negative cycle is reachable from the source, because otherwise V-1 rounds would already have fixed every distance.
Stopping Early When Nothing Changes
If a full pass relaxes no edge, later passes will not relax any either, because they read exactly the same distances. You can stop at that point. The worst case stays O(VE), but many inputs finish after a few passes.
Recovering Paths from Predecessors
Each time an edge (u, v) is relaxed, record pred[v] = u. To rebuild a path, start at the target, follow pred back to the source, and reverse the list.
Thinking in Intermediate Vertices: The Floyd-Warshall Recurrence
Let d_k(i, j) be the length of the shortest i-to-j path that uses only vertices 0..k-1 as intermediate vertices. Either the path avoids vertex k, or it passes through k once:
d{k+1}(i, j) = min(dk(i, j), dk(i, k) + dk(k, j))
The Floyd-Warshall Algorithm
The recurrence becomes three nested loops, and k must be the outermost loop. The algorithm runs in O(V³) time and can update a single matrix in place.
import math
def floyd_warshall(n, edges):
dist = [[math.inf] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u, v, w in edges:
dist[u][v] = min(dist[u][v], w)
for k in range(n):
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]
return dist
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
print(floyd_warshall(4, edges)[0]) # [0, 4, 1, 5]Exercise
A graph has 6 vertices and no negative cycles. What is the largest number of edges a shortest path can have, and how many relaxation rounds does Bellman-Ford need?
Show answer
A shortest path can be taken to be simple, so it has at most 5 edges. Bellman-Ford therefore needs at most 5 rounds, which is V-1.