Data Structures & AlgorithmsHardProduct Company SDE · BFS round

Problem: Fresh oranges (1) rot their neighbours (4-directional) one minute at a time; 0 is empty and 2 is rotten. How many minutes until no fresh orange remains (or -1 if impossible)? Run the multi-source BFS.

Problem: Fresh oranges (1) rot their neighbours (4-directional) one minute at a time; 0 is empty and 2 is rotten. How many minutes until no fresh orange remains (or -1 if impossible)? Run the multi-source BFS.
from collections import deque
g = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]
n, m = 3, 3
q = deque()
fresh = 0
for i in range(n):
    for j in range(m):
        if g[i][j] == 2:
            q.append((i, j, 0))
        elif g[i][j] == 1:
            fresh += 1
t = 0
while q:
    i, j, d = q.popleft()
    t = max(t, d)
    for a, b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
        if 0 <= a < n and 0 <= b < m and g[a][b] == 1:
            g[a][b] = 2
            fresh -= 1
            q.append((a, b, d + 1))
print(t if fresh == 0 else -1)
What is printed?
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. -1

Correct answer: A. 4

Each BFS layer is one minute, and the last fresh orange is reached at depth 4, so the answer is 4.

More Coding Interview Problems questions

Exams that ask this topic