Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

Floyd–Warshall on 4 vertices. What is the shortest distance from 0 to 3, and from 3 to 1?

Floyd–Warshall on 4 vertices. What is the shortest distance from 0 to 3, and from 3 to 1?
INF = float('inf')
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(d[0][3], d[3][1])
  1. A. 6 5
  2. B. 7 5
  3. C. 6 INF
  4. D. 6 8

Correct answer: A. 6 5

0 → 1 → 2 → 3 costs 3 + 2 + 1 = 6, better than the direct 7. 3 → 0 → 1 costs 2 + 3 = 5. The k loop must be outermost: after iteration k, paths may use intermediate vertices 0..k. O(V³).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic