This solution uses the Breadth-First Search (BFS) algorithm to simulate the rotting process of oranges. It starts by identifying all initially rotten oranges and counting fresh oranges. It enqueues all rotten oranges' positions. Using BFS, it iteratively infects fresh oranges adjacent to rotten ones each minute, marking them rotten and decreasing the fresh count. This continues until no fresh oranges are left or there are no more adjacent fresh oranges to infect, at which point the process stops. If any fresh oranges remain unreachable, it returns -1, otherwise, it returns the number of minutes passed.
时间复杂度: O(M * N)
空间复杂度: O(M * N)
# Class definition for the rotting oranges problem
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
M = len(grid) # Number of rows in the grid
N = len(grid[0]) # Number of columns in the grid
queue = [] # Queue to store positions of rotten oranges
count = 0 # Count of fresh oranges
for r in range(M):
for c in range(N):
if grid[r][c] == 1: # Count fresh oranges
count += 1
elif grid[r][c] == 2: # Initialize queue with all rotten oranges
queue.append((r, c))
def valid(x, y):
return 0<=x<M and 0<=y<N # Helper function to check boundaries
round = 0 # round represents the number of minutes passed
while count > 0 and len(queue) > 0: # While there are fresh oranges and rotten ones to process
round += 1
n = len(queue) # Number of oranges to process this round
for i in range(n):
r, c = queue.pop(0) # Pop the first rotten orange from the queue
for [x, y] in [[0,1], [0,-1], [1,0], [-1,0]]: # Check all 4 adjacent cells
new_x, new_y = r+x, c+y
if valid(new_x, new_y) and grid[new_x][new_y] == 1: # If adjacent cell is fresh
grid[new_x][new_y] = 2 # It rots
count -= 1 # Decrease count of fresh oranges
queue.append((new_x, new_y)) # Enqueue the newly rotten orange
if count > 0: # If there are still fresh oranges left
return -1 # It's impossible to rot all oranges
else:
return round # Return the total minutes required