ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
from collections import deque
def rot(g):
    R, C = len(g), len(g[0])
    q = deque()
    fresh = 0
    for r in range(R):
        for c in range(C):
            if g[r][c] == 2:
                q.append((r, c, 0))
            elif g[r][c] == 1:
                fresh += 1
    t = 0
    while q:
        r, c, d = q.popleft()
        t = max(t, d)
        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 g[nr][nc] == 1:
                g[nr][nc] = 2
                fresh -= 1
                q.append((nr, nc, d + 1))
    return t if fresh == 0 else -1
print(rot([[2, 1, 1], [1, 1, 0], [0, 1, 1]]), rot([[2, 1, 1], [0, 1, 1], [1, 0, 1]]))
  1. A. 4 4
  2. B. 3 -1
  3. C. -1 -1
  4. D. 4 -1

Correct answer: D. 4 -1

A BFS started from every rotten orange at once gives the minutes needed. The first grid rots completely in 4 minutes, while in the second a fresh orange is cut off, so the answer is -1.

More Python Programming questions

Exams that ask this topic