题目如下:
In a given grid, each cell can have one of three values:
- the value
0
representing an empty cell;- the value
1
representing a fresh orange;- the value
2
representing a rotten orange.Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return
-1
instead.Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]] Output: 4
Example 2:
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:
Input: [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j]
is only0
,1
, or2
.
解题思路:采用BFS的思想,依次把坏的橘子附近的好的橘子变成坏的橘子,求出最大值。有一点要注意的是,有些好橘子四周都是空格的话,这个橘子不会变坏。因此最后要计算剩余好橘子的数量,以此确定是否返回-1。
代码如下:
class Solution(object): def orangesRotting(self, grid): """ :type grid: List[List[int]] :rtype: int """ queue = [] #visit = [] fresh_count = 0 for i in range(len(grid)): #visit.append([0]*len(grid[i])) for j in range(len(grid[i])): if grid[i][j] == 2: queue.append((i,j,0)) elif grid[i][j] == 1: fresh_count += 1 res = 0 while len(queue) > 0: x,y,c = queue.pop(0) direction = [(0,1),(0,-1),(1,0),(-1,0)] for (i,j) in direction: if x + i >= 0 and x + i < len(grid) and y+j >=0 and y+j < len(grid[0]) and grid[x+i][y+j] == 1: queue.append((x+i,y+j,c+1)) grid[x + i][y + j] = 2 res = max(res,c+1) fresh_count -= 1 if fresh_count > 0: return -1 return res