Data Structures · Visualization
Floyd-Warshall
Graph
Floyd-Warshall finds the shortest paths between every pair of nodes in a graph all at once, rather than just from one source. Time: O(V^3). Space: O(V^2) for the distance table.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Floyd-Warshall
GraphFloyd-Warshall finds the shortest paths between every pair of nodes in a graph all at once, rather than just from one source. It works by considering each node, one at a time, as a possible 'stepping stone': for every pair of nodes, it checks whether routing the path through this stepping-stone node would be shorter than the current best-known path, and updates if so.
How Floyd-Warshall Works
- Build a distance table where distance[i][j] is the direct edge weight between i and j (or infinity if no direct edge, 0 if i equals j).
- For each node k (treated as a possible intermediate stepping stone), consider every pair of nodes (i, j).
- Check if the path i -> k -> j is shorter than the currently known distance[i][j].
- If it is, update distance[i][j] to that shorter value.
- After considering all nodes as stepping stones, the table holds shortest paths between every pair.
Floyd-Warshall Worked Example
Input: 3 nodes A, B, C with direct edges A-B(3), B-C(1), A-C(10)
- Initial: dist[A][C] = 10 (direct edge)
- Consider B as a stepping stone: dist[A][B] + dist[B][C] = 3 + 1 = 4
- 4 < 10, so update dist[A][C] = 4
Output: Shortest A-to-C distance updated from 10 to 4 (via B)
Press ▶ Run to watch it step by step.
def floyd_warshall(dist):
n = len(dist)
for k in range(n): # via vertex k
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
# example: Floyd-WarshallBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Floyd-Warshall Time & Space Complexity
When to Use Floyd-Warshall
- Precomputing all shortest routes on a small-to-medium road network
- Finding the 'transitive closure' of relationships (who can reach whom)
- Network analysis needing all pairwise shortest distances at once
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.