天天看点

Leetcode 994. Rotting Oranges

1. Description

Leetcode 994. Rotting Oranges

2. Solution

**解析:**Version 1,先统计新鲜水果数量,如果不存在,则时间为

,同时记录腐败水果的位置。按照广度优先搜索,记录下一轮腐败水果的位置,同时时间加

1

,新鲜水果数量减

1

,递归执行,直至不存在腐败的水果位置或者新鲜水果为

。如果此时仍存在新鲜水果,则返回

-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/