ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
from collections import deque
def max_dist(g):
    R, C = len(g), len(g[0])
    d = [[-1] * C for _ in range(R)]
    q = deque()
    for r in range(R):
        for c in range(C):
            if g[r][c] == 1:
                d[r][c] = 0
                q.append((r, c))
    while q:
        r, c = q.popleft()
        for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= nr < R and 0 <= nc < C and d[nr][nc] == -1:
                d[nr][nc] = d[r][c] + 1
                q.append((nr, nc))
    return max(max(row) for row in d)
print(max_dist([[0,0,0],[0,1,0],[0,0,0]]), max_dist([[1,0],[0,0]]))
  1. A. 2 1
  2. B. 1 2
  3. C. 3 2
  4. D. 2 2

Correct answer: D. 2 2

Multi-source BFS starts from every 1 at once. Corners of the 3x3 grid are 2 steps from the centre, and the far corner of the 2x2 grid is 2 steps from (0,0).

More Python Programming questions

Exams that ask this topic