ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from collections import deque
g = ["..#", ".#.", "..."]
d = [[-1] * 3 for _ in range(3)]
q = deque([(0, 0)])
d[0][0] = 0
while q:
    r, c = q.popleft()
    for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < 3 and 0 <= nc < 3 and g[nr][nc] == '.' and d[nr][nc] < 0:
            d[nr][nc] = d[r][c] + 1
            q.append((nr, nc))
print(d[2][2], d[0][1])
  1. A. -1 1
  2. B. 4 1
  3. C. 4 2
  4. D. 3 1

Correct answer: B. 4 1

BFS gives shortest path lengths on unit-weight grids. From (0,0) the cell (0,1) is one step away, and the route to (2,2) goes down the left column and then along the bottom row, which is 4 steps.

More Python Programming questions

Exams that ask this topic