LeetCode 994. Rotting Oranges
🧩 Problem Description
You are given an m x n
grid where each cell can have one of three values:
0
representing an empty cell,1
representing a fresh orange,2
representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange.
If it is impossible, return -1
.
💬 Examples
Example 1
1 | Input: grid = [[2,1,1],[1,1,0],[0,1,1]] |
Example 2
1 | Input: grid = [[2,1,1],[0,1,1],[1,0,1]] |
Example 3
1 | Input: grid = [[0,2]] |
💡 Intuition
This is a multi-source BFS problem.
- Each rotten orange is a BFS starting point.
- Use a queue to simulate the spread minute by minute.
- Track how many fresh oranges remain.
- If at the end some fresh oranges are left, return
-1
.
🔢 Java Code (BFS)
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(m × n), each cell is visited at most once.
- Space Complexity: O(m × n) for the BFS queue.
✍️ Summary
- Treat all rotten oranges as starting points.
- Run BFS layer by layer to simulate time passing.
- Return minutes when all fresh oranges are rotten, otherwise
-1
.
Related problems
lc-286
— Walls and Gateslc-542
— 01 Matrixlc-200
— Number of Islands