【BFS】腐爛的橘子

peterzh6發表於2024-04-29

https://leetcode.cn/problems/rotting-oranges/description/?envType=study-plan-v2&envId=top-100-liked

  1. 從一個點向上下左右移動並且判斷是否邊界可以用
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:
  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