題目出處
難度
medium
題目分類
Array, Breadth-First Search, Matrix
2026-10-13 二刷
個人範例程式碼 - 二刷 (2026/10/13)
from collections import deque
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
directions = [(1,0),(0,1),(-1,0),(0,-1)]
m, n = len(grid), len(grid[0])
count = 0
queue = deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
queue.append((i, j))
elif grid[i][j] == 1:
count += 1
minute = 0
while queue and count > 0:
for _ in range(len(queue)):
rotten_i, rotten_j = queue.popleft()
for di, dj in directions:
if 0 <= rotten_i+di < m and \
0 <= rotten_j+dj < n and grid[rotten_i+di][rotten_j+dj] == 1:
grid[rotten_i+di][rotten_j+dj] = 2
queue.append((rotten_i+di, rotten_j+dj))
count -= 1
minute += 1
return minute if count == 0 else -1
算法說明
BFS 的擴散問題,使用 queue 來保存前一個時間點的狀態
Time Complexity
O(mn)
沒有 4^L 是因為每個格子最多進 queue 一次(入列前就標成爛橘子的 2),不要用 DFS 去想
Space Complexity
O(mn) # queue 最多存 mn 個橘子座標
2026-07-25 一刷
個人範例程式碼 - 一刷 (2026/07/25)
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0 # no orange
h, w = len(grid), len(grid[0])
fresh_oranges = 0
curr_rotten_oranges = []
max_steps = 0
for i in range(h):
for j in range(w):
if grid[i][j] == 1:
fresh_oranges += 1
elif grid[i][j] == 2:
curr_rotten_oranges.append((i, j))
def valid_fresh_orange(i, j):
return 0 <= i < h and 0 <= j < w and grid[i][j] == 1
directions = [(1,0),(-1,0),(0,1),(0,-1)]
while fresh_oranges > 0 and curr_rotten_oranges:
next_rotten_oranges = []
for i, j in curr_rotten_oranges:
for dx, dy in directions:
if valid_fresh_orange(i+dx, j+dy):
grid[i+dx][j+dy] = 2
fresh_oranges -= 1
next_rotten_oranges.append((i+dx, j+dy))
curr_rotten_oranges = next_rotten_oranges
max_steps += 1
return -1 if fresh_oranges else max_steps
算法說明
這題偏複雜,直覺可能會想 DFS 但不對,
- DFS 解的意義會變成:我要找最深,也就是腐敗橘子最常鏈,但物理規則沒有繞遠路(最深),因此不該是 DFS
- BFS 透過分層(一層代表前進一步,腐敗多一層),找到最短次數
簡單來說 DFS 找最長、最深,BFS 找最短、最淺。
小技巧: Directions 先定義好,用 for dx, dy in directions 跑不同方向的更新
BFS 實作:This layer (此時間點),Next Layer (下一個時間點),然後交替直到無法再有更新
Time Complexity
O(m*n)
Space Complexity
O(m*n) 一樣有可能要幾乎把整個 grid 繞完
Boundary conditions
- 小心 [], [[]],not grid or not grid[0] 已經處理
Reference
<待補>