leetcode hot100 994. 腐烂的橘子 medium bfs


DFS 是一条路走到黑。而这道题要求的是**"最小分钟数",这本质上是在求最短路径/层数**,是 BFS

  1. 第一步:全员集合。先把网格里所有腐烂的橘子坐标都放进一个队列(Queue)里。

  2. 第二步:层层扩散。

    • 第 0 分钟:初始的腐烂橘子在队列里。
    • 第 1 分钟:这些橘子向四周扩散,把第一圈新鲜橘子变腐。
    • 第 2 分钟:新变腐的橘子再向外扩散......
  3. 这就是"层序遍历":每一分钟就是 BFS 的一层。


python 复制代码
from collections import deque


class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:

        rows, cols = len(grid), len(grid[0])
        queue = deque()
        fresh_count = 0

        # 1. 初始化:统计新鲜橘子数量,并将所有腐烂橘子入队
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    fresh_count += 1
                elif grid[r][c] == 2:
                    queue.append((r, c))   # 腐烂橘子(i,j)坐标

        # 如果没有新鲜橘子,直接返回 0
        if fresh_count == 0: 
            return 0

        minutes = 0
        # 2. 用 BFS 扩散腐烂橘子,直到没有腐烂或新鲜橘子
        while queue and fresh_count > 0:
            minutes += 1
            for _ in range(len(queue)):
                r, c = queue.popleft()  # 弹出一个腐烂橘子(i,j)坐标

                # 检查(r, c)的四个方向
                for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                    nr, nc = r + dr, c + dc

                    # 未出界,且如果是新鲜橘子,则变腐烂并入队
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                        grid[nr][nc] = 2
                        fresh_count -= 1   # 新鲜橘子-1
                        queue.append((nr, nc))   # 变腐烂并入队,待会继续腐烂别的橘子

        # 3. 最后检查是否还有新鲜橘子
        if fresh_count == 0: 
            return minutes 
        else:
            return -1

时间复杂度:O(mn),其中 m 和 n 分别为 grid 的行数和列数。

空间复杂度:O(mn)。

相关推荐
xlp666hub14 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
xlp666hub17 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
琢磨先生David11 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝11 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll11 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐11 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶12 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER12 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了12 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表