LeetCode 0994. Rotting Oranges腐爛的橘子【Easy】【Python】【BFS】
LeetCodepython
In a given grid, each cell can have one of three values:git
0
representing an empty cell;1
representing a fresh orange;2
representing a rotten orange.Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.github
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1
instead.app
Example 1:this
Input: [[2,1,1],[1,1,0],[0,1,1]] Output: 4
Example 2:spa
Input: [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:code
Input: [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:blog
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j]
is only 0
, 1
, or 2
.力扣three
在給定的網格中,每一個單元格能夠有如下三個值之一:隊列
0
表明空單元格;1
表明新鮮橘子;2
表明腐爛的橘子。每分鐘,任何與腐爛的橘子(在 4 個正方向上)相鄰的新鮮橘子都會腐爛。
返回直到單元格中沒有新鮮橘子爲止所必須通過的最小分鐘數。若是不可能,返回 -1
。
示例 1:
輸入:[[2,1,1],[1,1,0],[0,1,1]] 輸出:4
示例 2:
輸入:[[2,1,1],[0,1,1],[1,0,1]] 輸出:-1 解釋:左下角的橘子(第 2 行, 第 0 列)永遠不會腐爛,由於腐爛只會發生在 4 個正向上。
示例 3:
輸入:[[0,2]] 輸出:0 解釋:由於 0 分鐘時已經沒有新鮮橘子了,因此答案就是 0 。
提示:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j]
僅爲 0
, 1
, 或 2
BFS
先統計新鮮橘子個數 fresh,並把腐爛橘子個數放在隊列 q 中。 遍歷 q,每次彈出隊首元素,判斷四周有沒有新鮮橘子,並變爲腐爛,同時加入隊列 q,fresh 減 1。 當 q 爲空時表示已經所有腐爛。 每次遍歷都要判斷是否還有新鮮橘子剩餘,若是沒有新鮮橘子剩餘,直接返回 minute。 最後結束遍歷,還要單獨判斷是否有新鮮橘子剩餘(防止出現相似示例 2 這種永遠不會腐爛的橘子的狀況)。
時間複雜度: O(n*m),n 爲行數,m 爲列數。
空間複雜度: O(n*m),n 爲行數,m 爲列數。
class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) fresh = 0 q = [] # count fresh oranges and enqueue rotten oranges for i in range(n): for j in range(m): if grid[i][j] == 1: fresh += 1 elif grid[i][j] == 2: q.append((i, j)) if fresh == 0: return 0 dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)] minute = 0 # bfs while q: if fresh == 0: return minute size = len(q) for i in range(size): x, y = q.pop(0) for d in dirs: nx, ny = x + d[0], y + d[1] if nx < 0 or nx >= n or ny < 0 or ny >= m or grid[nx][ny] != 1: continue grid[nx][ny] = 2 q.append((nx, ny)) fresh -= 1 minute += 1 if fresh != 0: return -1