- 腐烂的橘子
在给定的网格中,每个单元格可以有以下三个值之一:
值 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotting-oranges
定义一个移动坐标表示四个方向的数组,然后 queue.append((i, j, time))
loc_x, loc_y, time = queue.pop(0)
深搜即可
class Solution(object):
def orangesRotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
x, y, time = len(grid), len(grid[0]), 0
queue = []
# 定义一个移动坐标的数组
locs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
for i in range(x):
for j in range(y):
if grid[i][j] == 2:
queue.append((i, j, time))
while queue:
loc_x, loc_y, time = queue.pop(0)
for loc in locs:
sur_x = loc_x + loc[0]
sur_y = loc_y + loc[1]
if 0 <= sur_x < x and 0 <= sur_y < y and grid[sur_x][sur_y] == 1:
grid[sur_x][sur_y] = 2
queue.append((sur_x, sur_y, time+1))
for row in grid:
if 1 in row:
return -1
return time