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

相关推荐
文丑颜不良啊15 分钟前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt17 分钟前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
文丑颜不良啊24 分钟前
LeetCode1341~1360题目解析
java·leetcode
海绵宝宝转agent1 小时前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
Pniubi3 小时前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
j7~19 小时前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
Shaoshing20 小时前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊21 小时前
LeetCode1261~1280题目解析
java·leetcode
Shaoshing1 天前
LeetCode100 11. 盛最多水的容器
算法·leetcode
海绵宝宝转agent1 天前
Leetcode二叉树算法个人理解
笔记·学习·算法·leetcode·深度优先