Question presented to candidate: "Explain the Floyd-Warshall algorithm. Implement it in Python for a directed weighted graph with V nodes, return the matrix of shortest distances between every pair, and tell me how you would detect a negative cycle."
What a strong answer should cover:
- The DP idea: after processing k,
dist[i][j]is the shortest path using only nodes 0..k as intermediates; the recurrencedist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). - The loop order: k must be the outermost loop, and why updating one matrix in place is safe.
- O(V³) time and O(V²) space; when it beats running Dijkstra from every node (small or dense graphs, negative weights).
- Negative weights are fine; a negative cycle shows up as
dist[i][i] < 0; anextmatrix rebuilds routes. - Python specifics:
float("inf")for missing edges, building the matrix with a list comprehension (not[[INF] * n] * n, which aliases rows), and pure-Python triple loops being slow for large V.
Clarifying questions expected:
- "How many nodes? Are negative weights or negative cycles possible?"
- "Do you need the routes, or only the distances?"
Code / implementation expected: Yes — a Python floyd_warshall(n, edges) returning the distance matrix, ideally plus a next matrix for route reconstruction.