# Floyd-Warshall's Algorithm

(Redirected from Floyd-Warshall)

The Floyd-Warshall Algorithm is an efficient algorithm to find all-pairs shortest paths on a graph. That is, it is guaranteed to find the shortest path between every pair of vertices in a graph. The graph may have negative weight edges, but no negative weight cycles (for then the shortest path is undefined).

This algorithm can also be used to detect the presence of negative cycles—the graph has one if at the end of the algorithm, the distance from a vertex ${\displaystyle v}$ to itself is negative.

## Algorithm

The Floyd-Warshall Algorithm is an application of Dynamic Programming.

Let ${\displaystyle dist(k,i,j)}$ be the the length of the shortest path from ${\displaystyle i}$ and ${\displaystyle j}$ that uses only the vertices ${\displaystyle v_{1},v_{2},\ldots ,v_{k}}$ as intermediate vertices. The following recurrence:

• ${\displaystyle k=0}$ is our base case - ${\displaystyle dist(0,i,j)}$ is the length of the edge from vertex ${\displaystyle i}$ to vertex ${\displaystyle j}$ if it exists, and ${\displaystyle \infty }$ otherwise.
• ${\displaystyle dist(k,i,j)=\min(dist(k-1,i,k)+dist(k-1,k,j),dist(k-1,i,j))}$: For any vertex ${\displaystyle i}$ and vertex ${\displaystyle j}$, the length of the shortest path from ${\displaystyle i}$ to ${\displaystyle j}$ with all intermediate vertices ${\displaystyle \leq k}$ simply does not involve the vertex ${\displaystyle k}$ at all (in which case it is the same as ${\displaystyle dist(k-1,i,j)}$), or that the shorter path goes through vertex ${\displaystyle k}$, so the shortest path between vertex ${\displaystyle i}$ and vertex ${\displaystyle j}$ is the combination of the path from vertex ${\displaystyle i}$ to ${\displaystyle k}$, and from vertex ${\displaystyle k}$ to ${\displaystyle j}$.

After ${\displaystyle N}$ iterations, there is no need anymore to go through any more intermediate vertices, so the distance ${\displaystyle dist(N,i,j)}$ represents the shortest distance between ${\displaystyle i}$ and ${\displaystyle j}$.

## Pseudocode

The pseudocode below assumes an input graph of N vertices.

for i = 1 to N
for j = 1 to N
if there is an edge from i to j
dist[0][i][j] = the length of the edge from i to j
else
dist[0][i][j] = INFINITY

for k = 1 to N
for i = 1 to N
for j = 1 to N
dist[k][i][j] = min(dist[k-1][i][j], dist[k-1][i][k] + dist[k-1][k][j])


This will give the shortest distances between any two nodes, from which shortest paths may be constructed.

This algorithm takes ${\displaystyle \Theta (N^{3})}$ time and ${\displaystyle \Theta (N^{3})}$ space, and has the distinct advantage of hiding a small constant in its behavior, since very little work is done in the innermost loop. Furthermore, the space-bound can be reduced further to ${\displaystyle \Theta (N^{2})}$ by noticing that ${\displaystyle dist(k,i,j)}$ is independent from ${\displaystyle dist(k-1,i,j)}$.