Graph Theory37 sections · 1633 units
Open in Course

Detecting Negative Cycles

(Checking the diagonal)

After running Floyd-Warshall, check the diagonal: if dist[i][i] < 0 for any ii, there is a negative cycle. Why?

A negative diagonal means you can start at ii, follow some cycle, and return to ii with negative total weight. If any dist[i][i] < 0, the graph contains a negative cycle and shortest paths are undefined. You can report this condition and stop. This check takes O(n)O(n) time after the main algorithm.

Space complexity is O(n2)O(n^2) for the distance matrix.