leetcode994. 腐烂的橘子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/87710343

在给定的网格中,每个单元格可以有以下三个值之一:
值 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

有点暴力:

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

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/87710343