封面

LeetCode 题解 · 腐烂的橘子

笔记日期
# LeetCode
# Python
# 广度优先搜索

如果先从一颗烂橘子一路传到底,再从另一颗出发,两边同时发生的传播就会被算成先后两段。用同一个队列装下所有起点。

一行 [2,1,1,1,2]。第一分钟,两端各染坏旁边一颗;第二分钟,最中间那颗也坏了。队列开头有几个点,就只处理几个,下一批要等下一分钟。

from collections import deque

class Solution:
    def orangesRotting(self, grid):
        m, n = len(grid), len(grid[0])
        q = deque((r, c) for r in range(m) for c in range(n) if grid[r][c] == 2)
        fresh = sum(row.count(1) for row in grid)
        minutes = 0
        while fresh and q:
            for _ in range(len(q)):
                r, c = q.popleft()
                for x, y in ((r-1,c), (r+1,c), (r,c-1), (r,c+1)):
                    if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
                        grid[x][y] = 2
                        fresh -= 1
                        q.append((x, y))
            minutes += 1
        return -1 if fresh else minutes

每个格子至多入队一次,时间 O(mn),队列空间 O(mn)。完全没有新鲜橘子时答案是 0;队列空了还有新鲜橘子,说明有空格把它隔开了。下面直接修改输入网格。

去力扣做第 994 题

返回 LeetCode 题单 →