Leetcode 994. Rotting Oranges

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 994. Rotting Oranges相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Rotting Oranges

2. Solution

**解析:**Version 1,先统计新鲜水果数量,如果不存在,则时间为0,同时记录腐败水果的位置。按照广度优先搜索,记录下一轮腐败水果的位置,同时时间加1,新鲜水果数量减1,递归执行,直至不存在腐败的水果位置或者新鲜水果为0。如果此时仍存在新鲜水果,则返回-1,否则,返回时间。

  • Version 1
class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        fresh = 0
        rotten = []
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 2:
                    rotten.append([i, j])
                elif grid[i][j] == 1:
                    fresh += 1
        if fresh == 0:
            return 0
        time = 0
        while rotten and fresh:
            temp = []
            for x, y in rotten:
                if x > 0 and grid[x-1][y] == 1:
                    grid[x-1][y] = 2
                    temp.append([x-1, y])
                    fresh -= 1
                if y > 0 and grid[x][y-1] == 1:
                    grid[x][y-1] = 2
                    temp.append([x, y-1])
                    fresh -= 1
                if x < m - 1 and grid[x+1][y] == 1:
                    grid[x+1][y] = 2
                    temp.append([x+1, y])
                    fresh -= 1
                if y < n - 1 and grid[x][y+1] == 1:
                    grid[x][y+1] = 2
                    temp.append([x, y+1])
                    fresh -= 1
            time += 1
            rotten = temp
        if fresh == 0:
            return time
        else:
            return -1

Reference

  1. https://leetcode.com/problems/rotting-oranges/

以上是关于Leetcode 994. Rotting Oranges的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 994. Rotting Oranges

Leetcode 994. Rotting Oranges

Leetcode-994 Rotting Oranges(腐烂的橘子)

Leetcode之广度优先搜索(BFS)专题-994. 腐烂的橘子(Rotting Oranges)

leetcode 994. 腐烂的橘子(Rotting Oranges)

994. Rotting Oranges[Medium]