CodeArchon

mediumGraphsAmazonFacebook

Citrus Spoilage Timer

A warehouse tracks how a mold outbreak on crate-stacked oranges spreads to all neighbors each minute.

In a grid, 0 = empty, 1 = fresh orange, 2 = rotten. Every minute, any fresh orange adjacent to a rotten one rots. Return the minutes until no fresh remain, or -1 if impossible.

Choose approach

🦠0
🍊
🍊
🍊
🍊
0
0
🍊
🍊
1/8
Narrationstep 1 of 8

Seed BFS from 1 rotten oranges. Fresh = 6.

1from collections import deque
2def orangesRotting(g):
3 R, C = len(g), len(g[0])
4 q = deque()
5 fresh = 0
6 for r in range(R):
7 for c in range(C):
8 if g[r][c] == 2: q.append((r, c, 0))
9 elif g[r][c] == 1: fresh += 1
10 t = 0
11 while q:
12 r, c, time = q.popleft(); t = time
13 for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
14 nr, nc = r+dr, c+dc
15 if 0<=nr<R and 0<=nc<C and g[nr][nc] == 1:
16 g[nr][nc] = 2; fresh -= 1
17 q.append((nr, nc, time + 1))
18 return -1 if fresh else t
Variables
fresh=6
rotten=1

How to think about it

  1. Multi-source BFS = each starting rot acts independently; BFS depth = time.
  2. Decrement fresh counter as neighbors rot.
  3. Non-zero fresh at end -> isolated -> -1.

Edge cases to catch in interview

  • No fresh oranges -> 0.
  • Only fresh, no rotten -> -1.

Examples

Example 14
{"grid":[[2,1,1],[1,1,0],[0,1,1]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed