The Floyd-Warshall algorithm is a classic graph theory algorithm used for finding the shortest paths between all pairs of vertices in a weighted graph. It is particularly useful when dealing with graphs that may contain negative weights, provided they do not contain any negative weight cycles.
The algorithm operates on an adjacency matrix representation of a graph. Each element graph[i][j] represents the weight of the direct edge from vertex i to vertex j. If there is no direct edge, it is typically represented by infinity (∞).
Floyd-Warshall uses dynamic programming to iteratively improve the shortest path estimates between all pairs of vertices. The core idea is to consider each vertex as an intermediate point and update the shortest paths accordingly.
Initialization:
dist with the same dimensions as the adjacency matrix.dist matrix.dist[i][i]) to 0, representing the distance from a vertex to itself.Iterative Relaxation:
(i, j), consider every other vertex k as an intermediate point.i and j if a shorter path is found through k.Path Reconstruction (Optional):
function FloydWarshall(graph):
V = number of vertices in graph
dist = copy of graph adjacency matrix
pred = initialize with None or special value indicating no path
for k from 0 to V-1:
for i from 0 to V-1:
for j from 0 to V-1:
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
pred[i][j] = k
return dist, pred
Here's a Python implementation of the Floyd-Warshall algorithm:
def floyd_warshall(graph):
V = len(graph)
dist = [row[:] for row in graph] # Copy the graph matrix
pred = [[None for _ in range(V)] for _ in range(V)]
# Initialize predecessor matrix
for i in range(V):
for j in range(V):
if i != j and graph[i][j] != float('inf'):
pred[i][j] = i
# Floyd-Warshall algorithm
for k in range(V):
for i in range(V):
for j in range(V):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
pred[i][j] = pred[k][j]
return dist, pred
# Example usage
graph = [
[0, 3, float('inf'), 7],
[8, 0, 2, float('inf')],
[5, float('inf'), 0, 1],
[2, float('inf'), float('inf'), 0]
]
distances, predecessors = floyd_warshall(graph)
print("Shortest distances:")
for row in distances:
print(row)
print("\nPredecessors for path reconstruction:")
for row in predecessors:
print(row)
float('inf') to represent non-existent edges, ensuring proper arithmetic operations.The Floyd-Warshall algorithm is a powerful tool for solving the all-pairs shortest path problem. Its ability to handle graphs with negative weights (excluding cycles) makes it versatile across various domains. By understanding its implementation and best practices, you can effectively apply this algorithm in real-world scenarios.