版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/87710343
示例 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
有点暴力:
import copy
class Solution:
def orangesRotting(self, grid: 'List[List[int]]') -> 'int':
res, x, y = 0, len(grid), len(grid[0])
new = copy.deepcopy(grid)
locs = [[-1, 0], [0, -1], [0, 1], [1, 0]]
while not self.noFresh(grid):
for i in range(x):
for j in range(y):
if grid[i][j] == 2:
for loc in locs:
loc_i, loc_j = i + loc[0], j + loc[1]
if 0 <= loc_i < x and 0 <= loc_j < y and grid[loc_i][loc_j] != 0:
new[loc_i][loc_j] = 2
res += 1
if grid == new:
break
grid = copy.deepcopy(new)
if not self.noFresh(grid):
return -1
return res
def noFresh(self, grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
return False
return True
将坏苹果入栈,直到栈空:
class Solution:
def orangesRotting(self, grid: 'List[List[int]]') -> 'int':
# 将坏苹果的位置和次数记录下来
x, y, res = len(grid), len(grid[0]), 0
locs, stack = [[-1, 0], [0, -1], [0, 1], [1, 0]], []
for i in range(x):
for j in range(y):
if grid[i][j] == 2:
stack.append((i, j, 0))
while stack:
i, j, res = stack.pop(0)
for loc in locs:
loc_i, loc_j = i+loc[0], j+loc[1]
if 0 <= loc_i < x and 0 <= loc_j < y and grid[loc_i][loc_j] == 1:
grid[loc_i][loc_j] = 2
stack.append((loc_i, loc_j, res+1))
for i in range(x):
for j in range(y):
if grid[i][j] == 1:
return -1
return res