994. Rotting Oranges
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
queue = deque()
fresh_oranges = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] == 2:
queue.append((row, col))
elif grid[row][col] == 1:
fresh_oranges += 1
directions = [(1,0), (-1,0), (0,1), (0,-1)]
mins = 0
if not queue and fresh_oranges > 0:
return -1
if fresh_oranges == 0:
return mins
# BFS
while queue and fresh_oranges > 0:
mins += 1
for _ in range(len(queue)):
row, col = queue.popleft()
for dr, dc in directions:
next_row = row + dr
next_col = col + dc
if 0 <= next_row < rows and 0 <= next_col < cols:
if grid[next_row][next_col] == 1:
queue.append((next_row, next_col))
grid[next_row][next_col] = 2
fresh_oranges -= 1
return mins if fresh_oranges == 0 else -1Last updated