Chapter 5 - Shortest Path
if best_so_far[u,w] > best_so_far[u,r] + best_so_far[r,w]:
best_so_far[u,w] = best_so_far[u,r] + best_so_far[r,w]def floyd_warshall(n, edge_cost):
# Initialize the path cost matrix with edge costs
path_cost = [[float('inf')] * n for _ in range(n)]
# Initialize the intermediate matrix with -1 (no intermediate nodes)
intermediate = [[-1] * n for _ in range(n)]
# Set initial path costs and intermediate nodes based on edge_costs
for i in range(n):
for j in range(n):
if i == j:
path_cost[i][j] = 0 # Cost to itself is 0
elif edge_cost[i][j] != float('inf'):
path_cost[i][j] = edge_cost[i][j]
intermediate[i][j] = i # Set intermediate to i if there's a direct edge
# Floyd-Warshall algorithm to find shortest paths
for k in range(n): # this loop iterates over each vertex k as a potential intermediate
for i in range(n): # this loop iterates over each vertex i as starting point
for j in range(n): # this loop iterates over each vertex j as ending point
# If a shorter path from i to j through k is found
if path_cost[i][j] > path_cost[i][k] + path_cost[k][j]:
path_cost[i][j] = path_cost[i][k] + path_cost[k][j]
intermediate[i][j] = k
return path_cost, intermediate
Last updated