Graph Theory37 sections · 1633 units
Open in Course

Floyd-Warshall vs Johnson's Algorithm

(Sparse graphs with negatives)

Johnson's algorithm solves all-pairs shortest paths in O(n2logn+nm)O(n^2 \log n + nm) time using Bellman-Ford once and Dijkstra nn times. For sparse graphs (mn2m \ll n^2), Johnson's is faster than Floyd-Warshall's O(n3)O(n^3).

For dense graphs or when simplicity matters, Floyd-Warshall is preferred. It also has better constants and is easier to implement. In a contest, I reach for Floyd-Warshall first if n500n \leq 500.

Space complexity is O(n2)O(n^2) for the data structures used.