All-pairs shortest paths via dynamic programming over allowed intermediates; handles negative edges and detects negative cycles by diagonal inspection.
Floyd–Warshall is a classic dynamic programming algorithm that computes shortest path distances between every pair of vertices in a weighted directed graph (including negative edge weights) in O(n^3)
time. It incrementally improves an n×n
distance matrix by allowing intermediate vertices in increasing order. After the main triple loop, a negative value on the diagonal indicates a negative cycle reachable for that vertex.
dist_k[i][j]
= shortest distance from i to j using only intermediate vertices from the set {1..k}dist_k[i][j] = min(dist_{k-1}[i][j], dist_{k-1}[i][k] + dist_{k-1}[k][j])
dist[i][i] < 0
after completion indicates a negative cycle reachable from i.next[i][j]
matrix (successor) updated on improvement.The cubic time arises from the triple nested loops over k, i, j. For n ≤ ~400 this can still be practical in educational or moderate analytic contexts. Space is dominated by the distance (and optional next) matrices.
Algorithm | Use Case | Neg Edges? | Negative Cycles? | Time |
---|---|---|---|---|
BFS | Unweighted SSSP | N/A | No | O(n+m) |
Dijkstra | Non-negative SSSP | No | No | O(m log n) |
Bellman-Ford | Negative edges SSSP | Yes | Detects | O(n·m) |
Floyd–Warshall | All-pairs, dense, negatives | Yes | Detects (diag<0) | O(n^3) |
Johnson | All-pairs sparse | Reweighted | Detects (BF stage) | O(n·m log n) |
Dive deeper into the DP formulation and see a matrix-evolution simulation of k-layer expansions.