【BFS】腐烂的橘子
https://leetcode.cn/problems/rotting-oranges/description/?envType=study-plan-v2&envId=top-100-liked
- 从一个点向上下左右移动并且判断是否边界可以用
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
nx = x + dx
ny = y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1:
- BFS常规技巧:多源广度优先 = 同层节点遍历 = 先获取队列
size
,然后弹出size
个元素,就可以恰好遍历完这个批次
的队列(哎呀好久没做题都忘光了XD,连这个都要写)
size = len(queue)
for _ in range(size):
x, y = queue.popleft()
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
queue = deque()
fresh_oranges = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 2:
queue.append((i, j))
elif grid[i][j] == 1:
fresh_oranges += 1
minutes = 0
if fresh_oranges == 0:
return 0
while queue:
size = len(queue)
for _ in range(size):
x, y = queue.popleft()
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
nx = x + dx
ny = y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1:
grid[nx][ny] = 2
queue.append((nx, ny))
fresh_oranges -= 1
if queue:
minutes += 1
return -1 if fresh_oranges != 0 else minutes