Floyd–Warshall Algorithm
Shortest distances between all pairs of vertices, in one dynamic-programming sweep.
Open on GeeksforGeeks ↗Intuition
Ask a smaller question: what is the shortest path from i to j if it may only route through vertices numbered below k? Start with k = 0 (direct edges only) and admit one more intermediate at a time. Admitting k either helps — via i→k→j — or it does not. After every vertex has been admitted, the matrix holds true shortest paths.
Approach
Initialise the matrix
d[i][j] = edge weight if one exists, 0 on the diagonal, ∞ otherwise. This is the answer when no intermediates are allowed.
Admit one intermediate at a time
For each k, for every pair (i, j): d[i][j] = min(d[i][j], d[i][k] + d[k][j]). The k-loop must be outermost — that is what makes the DP layer correct.
Negative cycles show on the diagonal
If any d[i][i] ends up negative, vertex i sits on a negative cycle: it can return to itself at a profit.
Solution & live demo
Edge cases
Swapping the loop order silently produces wrong answers — a classic bug.
Detected by a negative value on the diagonal.
Remain ∞.