from collections import deque
def orangesRotting(grid):
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
fresh_count = 0
rotten = deque()
# 找到所有腐烂的橘子和新鲜橘子的数量
for i in range(rows):
for j in range(cols):
if grid[i][j] == 2:
rotten.append((i, j))
elif grid[i][j] == 1:
fresh_count += 1
# 如果没有新鲜橘子,直接返回0
if fresh_count == 0:
return 0
minutes = 0
directions = [(1,0), (-1,0), (0,1), (0,-1)] # 上下左右四个方向
# BFS过程
while rotten and fresh_count > 0:
minutes += 1
# 处理当前层的所有腐烂橘子
for _ in range(len(rotten)):
x, y = rotten.popleft()
# 检查四个方向
for dx, dy in directions:
nx, ny = x + dx, y + dy
# 检查边界条件和是否是新鲜橘子
if (0 <= nx < rows and 0 <= ny < cols and
grid[nx][ny] == 1):
grid[nx][ny] = 2
fresh_count -= 1
rotten.append((nx, ny))
# 如果还有新鲜橘子,返回-1
return minutes if fresh_count == 0 else -1
# 测试
grid = [[1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[2, 1, 1, 1, 1, 1]]
result = orangesRotting(grid)
print(f"需要 {result} 分钟才能让所有橘子腐烂")
[[1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[2, 1, 1, 1, 1, 1]]