Problem Statement
You have a grid representing a box of oranges:
0= empty cell1= fresh orange2= rotten orange
Every minute, any fresh orange adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes until no fresh orange remains. If impossible, return -1.
Constraints
1 <= grid.length, grid[0].length <= 10grid[i][j]is0,1, or2
Example
Input:
grid = [[2,1,1],
[1,1,0],
[0,1,1]]
Output: 4
Explanation:
- Minute 1: oranges at (0,1) and (1,0) rot
- Minute 2: oranges at (0,2) and (1,1) rot
- Minute 3: orange at (2,1) rots
- Minute 4: orange at (2,2) rots
What the Interviewer Expects
- Multi-source BFS — start BFS from ALL rotten oranges simultaneously (not one at a time).
- Queue initialization — add all cells with value 2 to the queue at the start.
- Track time — each BFS level = 1 minute.
- Check completion — after BFS, scan grid for any remaining fresh oranges → return -1 if found.
- Time: O(mn), Space: O(mn)
Follow-ups
- What if rotting also spreads diagonally (8 directions)? How does time change?
- What if some cells have "walls" that block rotting?
- What if you can place one additional rotten orange anywhere — where should you place it to minimize total time?
- Can you solve this with DFS? Why is BFS preferred here?