Skip to main content

Floyd-Warshall Algorithm

Definition​

The Floyd-Warshall algorithm is a dynamic programming technique used to find the shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). It efficiently computes the shortest paths between all pairs of vertices in a graph, making it suitable for problems where the shortest distances between all pairs of vertices are required

Practice​

FloydWarshall(graph):
n = number of vertices in the graph
distance[][] = initialize distance matrix with direct edge weights

// Compute shortest paths
for k from 1 to n:
for i from 1 to n:
for j from 1 to n:
// If vertex k is on the shortest path from i to j
if distance[i][k] + distance[k][j] < distance[i][j]:
distance[i][j] = distance[i][k] + distance[k][j]

return distance