[leetcode]994. Rotting Oranges @ python

原题

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

解法

BFS. 首先遍历grid, 统计新鲜橘子的个数, 将腐烂橘子的index放入q. Edge case是当grid没有新鲜橘子时, 返回0. 然后使用BFS, 依次将腐烂橘子的index弹出, 查找四周的新鲜橘子并把它们变成腐烂橘子, 遍历一次后ans递增.当跳出循环后发现新鲜橘子的个数>0时, 返回-1. 由于在最后一次循环中已没有可以转化为腐烂橘子的新鲜橘子, ans多算了一次, 因此返回ans-1.

代码

class Solution(object):
    def orangesRotting(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        row, col = len(grid), len(grid[0])
        q = collections.deque()
        fresh = 0
        ans = 0
        for i in range(row):
            for j in range(col):
                if grid[i][j] == 1:
                    fresh += 1
                elif grid[i][j] == 2:
                    q.append((i, j))
                    
        # edge case: no fresh orange
        if fresh == 0: return 0
        
        while q:
            for _ in range(len(q)):
                x, y = q.popleft()
                for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
                    if 0<=x+dx<row and 0<=y+dy<col and grid[x+dx][y+dy] == 1:
                        grid[x+dx][y+dy] = 2
                        q.append((x+dx, y+dy))
                        fresh -= 1
            ans += 1
        return ans -1 if fresh == 0 else -1

你可能感兴趣的:([leetcode]994. Rotting Oranges @ python)