Model answer
Let Dᵏ[i][j] be the shortest i→j path using only vertices 1…k as intermediates. Then Dᵏ[i][j]=min(Dᵏ⁻¹[i][j], Dᵏ⁻¹[i][k]+Dᵏ⁻¹[k][j]); implementing k as the outer loop gives O(V³).
Use the key terms, then explain the reasoning.
Floyd–Warshall computes all-pairs shortest paths by progressively allowing each vertex as an intermediate.
Floyd–Warshall defines dist_k(i,j) as the best path whose intermediate vertices come only from the first k vertices. A best path either avoids vertex k or splits into i→k and k→j paths that use earlier intermediates.
The algorithm supports negative edges because it does not greedily finalise distances. After completion, a negative diagonal entry indicates a reachable negative cycle affecting shortest-path meaning.
Allow one intermediate
| Operation | Best | Average | Worst | Extra space |
|---|---|---|---|---|
| All-pairs shortest paths | O(V³) | O(V³) | O(V³) | O(V²) |
Guarding INF prevents overflow when one half of a candidate route does not exist.
Open a prompt when you are ready to check your answer.