Rotting Oranges Problem
Description
LeetCode Problem 994.
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, or
- 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 this is impossible, return -1.
Example 1:
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 10
- grid[i][j] is 0, 1, or 2.
Solution
Approach: Multi-Source BFS
Rot spreads one step per minute in all four directions, which is exactly how breadth-first search expands one layer at a time. The only twist is that there can be many rotten oranges at the start, and they all spread at the same time. So put all of them into the queue before the BFS begins (a multi-source BFS); running a separate BFS from each one would not model the simultaneous spread.
- Scan the grid: add every rotten orange to the queue and count the fresh ones in
fresh. - While the queue is not empty and
fresh > 0, process one minute: take exactly the oranges that are in the queue now, and for each fresh neighbor, mark it rotten, decreasefresh, and add it to the queue. Then increaseminutes. - If
fresh == 0, returnminutes; otherwise some orange can never be reached, so return-1.
Processing the queue level by level is what turns BFS layers into minutes. Mark a neighbor rotten when it is added to the queue, not when it is taken out, or two rotten oranges could both add it in the same minute.
The loop condition fresh > 0 matters for the edge cases: with no fresh oranges at all (Example 3, or a grid of only empty cells) the answer is 0 even if there is nothing rotten, and the BFS must not count a final minute in which nothing new rots.
Complexity: O(m · n) time and O(m · n) space for the queue, where m and n are the grid's dimensions.
import collections
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
queue = collections.deque() # rotten oranges whose neighbors are still to be checked
fresh = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
fresh += 1
minutes = 0
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while queue and fresh > 0:
# everything in the queue now rots its neighbors during this minute
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1