Rotten Oranges

medium

Given an R × C grid where each cell is 0 (empty), 1 (fresh orange), or 2 (rotten orange), every minute any fresh orange 4-directionally adjacent to a rotten one becomes rotten. Return the minimum number of minutes until no fresh orange remains, or -1 if that's impossible.

Hints

All rotten oranges spread at the same time — seed them all into one BFS at minute 0.
Each BFS layer corresponds to one minute.
Track the fresh count; if any remain unreached, return -1.

Common doubts

Rot spreads from every rotten orange simultaneously, so all of them must be at distance 0; a single source would overstate the time.
Count fresh oranges initially and decrement as they rot; any left after BFS can never be reached.
0 — nothing needs to rot.

Interview follow-ups

Use 8 directions; more oranges become reachable and times shrink.
After BFS, the cells still equal to 1 are exactly those.

Fun facts

  • LeetCode 994 — the archetypal multi-source BFS problem.
  • The same 'seed all sources' idea solves nearest-distance and fire-spread grids.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Rot spreads outward; the last fresh orange rots at minute 4.
Example 2
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
The bottom-left orange is never adjacent to rot.
Constraints

- 1 <= R, C <= 300 - grid[i][j] is 0, 1, or 2

Solve this problem →