Rotting Oranges
Medium · Graphs · Array · BFS · Matrix
Problem
A grid holds 0 (empty), 1 (fresh orange) or 2 (rotten orange). Each minute, every fresh orange adjacent to a rotten one (up, down, left, right) becomes rotten.
Return the minutes until no fresh orange remains, or -1 if some can never rot.
Examples
Input: grid = [[2,1,1],[1,1,0],[0,1,1]] Output: 4
Rot spreads outward from the single source.
Input: grid = [[2,1,1],[0,1,1],[1,0,1]] Output: -1
The bottom-left orange is unreachable.
Input: grid = [[0,2]] Output: 0
No fresh oranges to begin with.
Constraints
- 1 <= rows, cols <= 10
- grid[i][j] is 0, 1 or 2
Approaches
- Repeated sweeps over the grid — time O((rows · cols)²), space O(1)
Related problems
Start free on Cariara · Coding problems · System design studio