QueueMedium

Rotting Oranges Visualizer

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

A queue is the right structure because oranges that rot in the same minute must be processed before the next minute.

Visualization & algorithm

The grid, and the queue of rotten cells
queue every rotten cell at minute 0
while queue:
rot the four neighbors that are fresh
push them at minute + 1
if fresh remain: return -1 else return minutes
Step 0/0 Answer —

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

PieceCostWhy
TimeO(rows * cols)Each cell enters the queue at most once.
SpaceO(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