26. Floyd-Warshall Algorithm
Description
The Floyd-Warshall Algorithm is an all-pairs shortest path algorithm used for finding the shortest paths between every pair of vertices in a weighted graph. Unlike Dijkstra's algorithm, which finds the shortest path from a single source vertex to all other vertices, the Floyd-Warshall algorithm computes shortest paths between every pair of vertices simultaneously. It works with both positive and negative edge weights, provided the graph contains no negative-weight cycles.
This algorithm is ideal for scenarios where the shortest distances between all pairs of vertices must be precomputed. It utilizes dynamic programming to update a distance matrix by systematically testing every vertex as a potential intermediate path node.
Steps of the Floyd-Warshall Algorithm:
- Initialize the distance matrix:
- For every pair of vertices (i, j), set
dist[i][j]to the edge weight between them. - If no edge exists between i and j, set
dist[i][j]to infinity (∞). - Set the distance from any vertex to itself to zero (
dist[i][i] = 0).
- Iterative Distance Update:
- For each vertex k acting as an intermediate node, update the distance between all vertex pairs (i, j) by checking if passing through k yields a shorter path:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
- Repeat: Repeat this process for all candidate intermediate vertices k = 0, 1, …, n-1 to compute the final matrix of all-pairs shortest paths.
Step-by-Step Explanation
- Initialization:
We construct an n × n distance matrix. Main diagonal entries are set to 0 (distance to self). For all other vertex pairs, if a direct edge exists, its weight is recorded; otherwise, the value is set to infinity (INF).
- Distance Updates:
At each step k, the algorithm evaluates whether traveling from vertex i to vertex j through an intermediate vertex k produces a smaller total distance than the current best-known path dist[i][j].
- Completion:
After trying every vertex k as an intermediate node, the matrix contains the shortest path distances between all vertex pairs.
Example Output
Shortest Paths Matrix:
[0, 3, 4, 10, 6, 6]
[3, 0, 1, 7, 3, 4]
[4, 1, 0, 7, 3, 4]
[10, 7, 7, 0, 2, 3]
[6, 3, 3, 2, 0, 3]
[6, 4, 4, 3, 3, 0]
Python Implementation
INF = float('inf')
def floyd_warshall(graph):
# graph: adjacency matrix where graph[i][j] is edge weight from i to j.
# If no edge exists, graph[i][j] should be set to float('inf').
n = len(graph)
dist = [[INF] * n for _ in range(n)]
# Fill in base distances for direct edges and self-loops
for i in range(n):
for j in range(n):
if i == j:
dist[i][j] = 0
elif graph[i][j] != 0: # If an edge exists between i and j
dist[i][j] = graph[i][j]
# Floyd-Warshall core algorithm
for k in range(n): # Intermediate vertex
for i in range(n): # Source vertex
for j in range(n): # Destination vertex
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
# Example usage:
graph = [
[0, 3, INF, INF, INF, INF], # Vertex 0 connected to 1 (weight 3)
[3, 0, 1, INF, INF, INF], # Vertex 1 connected to 2 (weight 1)
[INF, 1, 0, 7, INF, INF], # Vertex 2 connected to 3 (weight 7)
[INF, INF, 7, 0, 2, 3], # Vertex 3 connected to 4 (weight 2) & 5 (weight 3)
[INF, INF, INF, 2, 0, 3], # Vertex 4 connected to 3 (weight 2) & 5 (weight 3)
[INF, INF, INF, 3, 3, 0] # Vertex 5 connected to 3 (weight 3) & 4 (weight 3)
]
distances = floyd_warshall(graph)
print("Shortest Paths Matrix:")
for row in distances:
print(row)
Complexity
- Time Complexity: O(n³), where n is the number of vertices in the graph, due to the triple nested loop iterating over all vertices for each intermediate candidate step.
- Space Complexity: O(n²), as it requires an n × n distance matrix to store all-pairs shortest path weights.
Applications of the Floyd-Warshall Algorithm
- Graphs with Negative Edge Weights: Unlike Dijkstra's algorithm, Floyd-Warshall handles graphs with negative edge weights seamlessly, provided there are no negative-weight cycles.
- Network Routing: Used for computing all-pairs shortest paths in transportation, logistics, and telecommunications networks.
- Precomputing Routing Tables: Useful in static network environments where shortest paths between all node pairs need to be calculated once and queried frequently.
- Graph Structural Analysis: Frequently applied in computing graph transitive closures, graph diameter, and connectivity properties.
Conclusion
The Floyd-Warshall algorithm offers a clean and structured dynamic programming solution for calculating all-pairs shortest paths, making it a foundational tool in graph theory, network design, and algorithm analysis.
All rights remain with the original author (Archiveskk). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me