Asked at

Rotting Oranges

Medium
Verified
BFSMatrixQueue~25 min

Each minute, every rotten orange (2) rots its 4-directional fresh (1) neighbours. Empty cells are 0.

Return the minutes until no fresh orange remains, or -1 if some fresh orange can never rot. The input is the grid number[][] directly.

Examples

in[[2,1,1],[1,1,0],[0,1,1]]
out4

After 4 minutes every fresh orange has rotted.

in[[2,1,1],[0,1,1],[1,0,1]]
out-1

The bottom-left orange is isolated and never rots.

Constraints

  • 1 ≤ rows, cols ≤ 10
  • grid[r][c] is 0 (empty), 1 (fresh), or 2 (rotten).
  • Rot spreads 4-directionally, one cell per minute.

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.