What is Rotting Oranges
Every minute, a rotten orange rots its fresh neighbors in the four directions. Return how many minutes until every fresh orange is rotten. If some fresh orange can never rot, return -1.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(rows * cols) | Each cell enters the queue at most once. |
| Space | O(rows * cols) | The queue can hold a whole layer. |
Implementation
from collections import deque
def solve(self, grid):
rows, cols = len(grid), len(grid[0])
q, fresh = deque(), 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 2: q.append((i, j, 0))
elif grid[i][j] == 1: fresh += 1
minutes = 0
while q:
i, j, m = q.popleft()
minutes = m
for di, dj in ((1,0),(-1,0),(0,1),(0,-1)):
ni, nj = i+di, j+dj
if 0 <= ni < rows and 0 <= nj < cols and grid[ni][nj] == 1:
grid[ni][nj] = 2
fresh -= 1
q.append((ni, nj, m+1))
return -1 if fresh else minutes