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])- A. 6 5
- B. 7 5
- C. 6 INF
- 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³).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)? python edges = [(0, 1…
- What is printed? (detect a cycle in an undirected graph with union-find) python def hascycle(n, edges): p = list(range(n)) def f(x): while…
- What is printed? (number of paths from source to target in a DAG with memoisation) python from functools import lrucache g = {0: [1, 2…
- What is printed? (longest path in a DAG using topological order) python g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1)…
- What is printed? (unique paths count with memoised recursion vs closed form) python from functools import lrucache from math import comb…
- What is printed? (LIS length with O(n²) DP and the number of LIS) python a = [1, 3, 5, 4, 7] n = len(a); L = [1] n; C = [1] n for i in…