Problem description:

In a given grid, each cell can have one of three values:

the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) 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 instead.

Example 1:

1
2
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example 2:

1
2
3
Input: [[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:

1
2
3
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

Note:

  1. 1 <= grid.length <= 10
  2. 1 <= grid[0].length <= 10
  3. grid[i][j] is only 0, 1, or 2.

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# 1. find all rotten orange
# 2. for each rotten orange, do bfs
# 2.1 the rotten orange is added based on level
# ex: at first, there're only 3 rotten orange, then just do 3 times BFS
# 2.2 add new rotten orange to queue
m = len(grid)
if m == 0:
return -1
n = len(grid[0])

queue = deque()
fresh_orange = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
queue.append((i, j))
if grid[i][j] == 1:
fresh_orange += 1

minute_passed = 0
while queue and fresh_orange > 0:
minute_passed += 1
for _ in range(len(queue)):
x, y = queue.popleft()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
xx, yy = x + dx, y + dy
if xx < 0 or yy < 0 or xx == m or yy == n:
continue
if grid[xx][yy] == 0 or grid[xx][yy] == 2:
continue

grid[xx][yy] = 2
fresh_orange -= 1
queue.append((xx, yy))
return minute_passed if fresh_orange == 0 else -1

time complexity: $O(mn)$, each cell is visited at least once

space complexity: $O(mn)$, in the worst case if all the oranges are rotten they will be added to the queue

reference:
https://leetcode.com/problems/rotting-oranges/discuss/563686/Python-Clean-and-Well-Explained-(faster-than-greater-90)

related problem: