InterviewPrepKit

Home / Coding / Graphs

Rotting Oranges

medium Original ↗
Solving tips
  • Rot spreads from all rotten oranges simultaneously, which is exactly multi-source BFS: seed the queue with every rotten orange at level 0 and count levels; O(m*n).
  • Freeze the level size with 'for _ in range(len(queue))' each minute so oranges rotted this minute don't get counted into the same minute.
  • Count fresh oranges up front and decrement as each rots; after BFS, any remaining fresh means unreachable so return -1.
  • Pitfall: handle the no-fresh case as 0 minutes, and rot/mark a cell when you enqueue it to avoid double processing.

Problem

You’re given an m x n grid where each cell is:

  • 0 — empty,
  • 1 — a fresh orange,
  • 2 — a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent (up/down/left/right) to a rotten orange becomes rotten. Return the minimum number of minutes that must pass until no fresh orange remains. If some fresh orange can never rot, return -1.

Examples

  • grid = [[2,1,1],[1,1,0],[0,1,1]]4 — rot spreads outward from the top-left; the last fresh orange (bottom-right) rots at minute 4.
  • grid = [[2,1,1],[0,1,1],[1,0,1]]-1 — the fresh orange at the bottom-left corner is isolated by empty cells and never rots.
  • grid = [[0,2]]0 — there are no fresh oranges to begin with, so zero minutes pass.

Constraints

  • 1 <= m, n <= 10
  • Each cell is 0, 1, or 2.
  • Rot spreads to all four neighbors simultaneously each minute.

Think about it first

Hint 1 All currently-rotten oranges spread at the same time each minute. That "everything at distance 1, then everything at distance 2" expansion is exactly what one traversal does naturally.
Hint 2 Breadth-first search, seeded with *every* rotten orange at once (multi-source BFS). Each BFS "level" is one minute. The number of levels until the queue drains is the elapsed time.
Hint 3 Count fresh oranges up front. Run the level-by-level BFS, decrementing the fresh count as each orange rots. At the end, if any fresh remain, some were unreachable → return `-1`; otherwise return the number of minutes elapsed.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.