PracticeNeetCode ↗LeetCode ↗
Given a grid where 0 is empty, 1 is a fresh orange, and 2 is a rotten orange, every minute any fresh orange 4-directionally adjacent to a rotten one becomes rotten. Return the minimum minutes until no fresh orange remains, or -1 if that's impossible.
Time: O(rows · cols) — Space: O(rows · cols)
from collections import deque
def orangesRotting(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
queue = deque()
fresh = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
fresh += 1
minutes = 0
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while queue and fresh > 0:
minutes += 1
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
return minutes if fresh == 0 else -1How the solution above works, piece by piece.
while queue and fresh > 0: each pass of the outer loop is one minute.for _ in range(len(queue)) handles exactly the oranges that rotted in the previous minute; their fresh neighbours rot now and are queued for the next minute.fresh.Running it on grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]: