題目出處
難度
medium
題目分類
Array, Breadth-First Search, Matrix
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
<待補>