The Floyd-Warshall Algorithm is a fundamental graph algorithm used to compute the shortest paths between all pairs of nodes in a weighted graph. It is highly effective in scenarios involving dense graphs and extensive node interactions.
The algorithm systematically checks if a better path exists through an intermediate node. Think of it as navigating a city: Instead of driving directly, you check if passing through a key intersection could reduce your travel time.
D[i][j] = min(D[i][j], D[i][k] + D[k][j])
(A) --3--> (B)
| /
8 1
| /
(C) <--5-- (D)
Initial Distance Matrix:
[ 0 3 ∞ ∞ ]
[ ∞ 0 ∞ 1 ]
[ ∞ ∞ 0 5 ]
[ ∞ ∞ ∞ 0 ]
Step-by-Step Distance Matrix Updates:
After processing each intermediate node:
Step 1: [ 0 3 ∞ 4 ]
Step 2: [ ∞ 0 ∞ 1 ]
Step 3: [ ∞ ∞ 0 5 ]
Step 4: [ ∞ ∞ ∞ 0 ]
Final Distance Matrix:
[ 0 3 ∞ 4 ]
[ ∞ 0 ∞ 1 ]
[ ∞ ∞ 0 5 ]
[ ∞ ∞ ∞ 0 ]
In addition to distances, you can track the predecessor matrix to reconstruct the optimal path between nodes.
def floyd_warshall(graph):
dist = list(map(lambda p: list(map(lambda q: q, p)), graph))
V = len(graph)
for k in range(V):
for i in range(V):
for j in range(V):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist