In computer science, the Floyd–Warshall algorithm (also known as Floyd’s algorithm, the Roy–Warshall algorithm, the Roy–Floyd algorithm, or the WFI algorithm) is an algorithm for finding shortest paths in a directed weighted graph with positive or negative edge weights (but with no negative cycles).
Algorithm
- Initialize distances
distance
is a \(|V| \times |V|\) matrix with values initialized to \(\infty\)distance[u][v] = edge[u][v]
distance[u][u] = 0
- Nested: for k, i, j from 1 to \(|V|\), do
candidate_distance = distance[i][k] + distance[k][j]
distance[i][j] = candidate_distance if distance[i][j] < candidate_distance
In pseudocode:
let dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity) for each edge (u, v) do dist[u][v] ← w(u, v) // The weight of the edge (u, v) for each vertex v do dist[v][v] ← 0 for k from 1 to |V| for i from 1 to |V| for j from 1 to |V| if dist[i][j] > dist[i][k] + dist[k][j] dist[i][j] ← dist[i][k] + dist[k][j] end if
Complexity
- Time: \(\bigtheta{|V|^3}\)
- Space: \(\bigtheta{|V|^2}\)
Bibliography
“FloydWarshall Algorithm.” 2022. Wikipedia, September. https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1113259725.