Graph Theory37 sections · 1633 units
Open in Course

The All-Pairs Problem

Finding every pair's distance

The all-pairs shortest path problem asks: what is the shortest distance between every pair of vertices in the graph?

If you have nn vertices, you need to compute n2n^2 distances. One approach is to run Dijkstra from each vertex, giving O((n2+nm)logn)O((n^2 + nm) \log n) time. Floyd-Warshall solves this in O(n3)O(n^3) time with simpler code and handles negative edges (as long as no negative cycles exist). For dense graphs or when you need all distances, Floyd-Warshall is the standard choice.

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