Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA

Floyd–Warshall is run on the 4-vertex directed weighted graph with matrix rows [0,3,∞,7], [8,0,2,∞], [5,∞,0,1], [2,∞,∞,0]. Sum the final shortest distances over all ordered pairs (i, j) with a finite distance, including i = j. Run the code.

Floyd–Warshall is run on the 4-vertex directed weighted graph with matrix rows [0,3,∞,7], [8,0,2,∞], [5,∞,0,1], [2,∞,∞,0]. Sum the final shortest distances over all ordered pairs (i, j) with a finite distance, including i = j. Run the code.
INF=10**9
d=[[0,3,INF,7],[8,0,2,INF],[5,INF,0,1],[2,INF,INF,0]]
n=4
for k in range(n):
    for i in range(n):
        for j in range(n):
            if d[i][k]+d[k][j]<d[i][j]: d[i][j]=d[i][k]+d[k][j]
print(sum(d[i][j] for i in range(n) for j in range(n) if d[i][j]<INF))
What is printed?
  1. A. 50
  2. B. 48
  3. C. 16
  4. D. 28

Correct answer: B. 48

Floyd–Warshall must loop over the intermediate vertex k as the outermost loop, which the stem's order satisfies. Moving k inside gives wrong distances, counting reachable pairs instead of summing distances is a different quantity, and skipping the relaxation leaves the direct edge weights.

More Coding Interview Problems questions

Exams that ask this topic