Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if impossible)?

Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if impossible)?
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, t = q.popleft()
        for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= x < R and 0 <= y < C and g[x][y] == 1:
                g[x][y] = 2; fresh -= 1; q.append((x, y, t + 1))
    return t if fresh == 0 else -1
print(rot([[2,1,0,2],[1,0,1,1],[1,1,0,1]]))
What is printed?
  1. A. 4
  2. B. 2
  3. C. -1
  4. D. 3

Correct answer: D. 3

Multi-source BFS from both rotten oranges: minute 1 rots (0,1), (1,0), (1,3); minute 2 rots (2,0), (1,2), (2,3); minute 3 rots (2,1). All 7 fresh oranges are reached, so the answer is 3.

More Coding Interview Problems questions

Exams that ask this topic