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)。

相关推荐
一只齐刘海的猫19 小时前
【Leetcode】移动零
算法·leetcode·职场和发展
人道领域19 小时前
【LeetCode刷题日记】131.分割回文串,动态规划优化
java·开发语言·leetcode
Lsk_Smion21 小时前
力扣实训 _ [994].腐烂的橘子/图论
算法·leetcode·图论
8Qi81 天前
LeetCode 337:打家劫舍 III(House Robber III)—— 题解 ✅
算法·leetcode·二叉树·动态规划
2601_961194021 天前
教资科三美术考什么|初中高中美术题型考点和模板资料
leetcode·elasticsearch·职场和发展·蓝桥杯·pat考试·lucene
8Qi81 天前
LeetCode 121 & 122:股票买卖问题(DP 对比题解)✅
算法·leetcode·职场和发展·动态规划
一只齐刘海的猫1 天前
【Leetcode】 接雨水
java·算法·leetcode
菜菜的顾清寒1 天前
力扣HOT(100)54多维动态规划-最长公共子序列
算法·leetcode·动态规划
txzrxz1 天前
广度优先搜索详解(BFS)
算法·宽度优先
8Qi81 天前
LeetCode 198:打家劫舍(House Robber)—— 题解 ✅
算法·leetcode·动态规划