LeetCode994腐烂的橘子

题目描述

  在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:值 0 代表空单元格;值 1 代表新鲜橘子;值 2 代表腐烂的橘子。每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。

解析

  对于每一个腐烂的橘子,每次都使其周围的橘子变成腐烂的橘子,就是同时又多个起点的BFS算法,有点类似洪泛这种。

复制代码
public int orangesRotting(int[][] grid) {
    Queue<int[]> queue = new ArrayDeque<>();
    int freshOranges = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == 2) {
                queue.offer(new int[]{i, j});
            } else if (grid[i][j] == 1) {
                freshOranges++;
            }
        }
    }

    if (freshOranges == 0) return 0;
    int minutes = 0;

    int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    while (!queue.isEmpty()) {
        int currentLevelSize = queue.size();
        for (int i = 0; i < currentLevelSize; i++) {
            int[] cur = queue.poll();
            for (int[] direction : directions) {
                int newX = cur[0] + direction[0];
                int newY = cur[1] + direction[1];
                if (newX >= 0 && newX < grid.length && newY >= 0 && newY < grid[0].length && grid[newX][newY] == 1) {
                    grid[newX][newY] = 2;  // Mark as rotten
                    queue.offer(new int[]{newX, newY});
                    freshOranges--;
                }
            }
        }
        minutes++;  // Completed one minute
    }

    return freshOranges == 0 ? minutes - 1 : -1;  // Adjust minutes as the last minute may not count
}
相关推荐
whaledown4 分钟前
Kafka 与 Java 消息队列入门:用订单场景理解核心机制
java·kafka·消息队列·springboot
Moshow郑锴8 分钟前
Ubuntu用SDKMAN轻松管理多个Java 版本
java·ubuntu·sdkman
生成论实验室10 分钟前
自动驾驶:一个自主运动的系统
人工智能·算法·机器学习·语言模型·机器人·自动驾驶·安全架构
sheeta199812 分钟前
LeetCode 每日一题笔记 日期:2026.06.16 题目:3612. 字符串特殊符号处理
笔记·算法·leetcode
阿昌喜欢吃黄桃13 分钟前
RocketMq事务消息原理
java·中间件·消息队列·rocketmq·mq
CoderYanger16 分钟前
A.每日一题:2095. 删除链表的中间节点
java·数据结构·程序人生·leetcode·链表·面试·职场和发展
摇滚侠19 分钟前
MyBatis+Spring+SpringMVC SSM 整合 179-185
java·spring·mybatis
青山木20 分钟前
Hot 100 --- 矩阵置零
线性代数·算法·leetcode·矩阵·哈希算法
Jasmine_llq21 分钟前
《B4264 [GESP202503 四级] 二阶矩阵》
线性代数·算法·矩阵·二维矩阵遍历枚举所有2×2矩阵·交叉乘积等式条件判断·输入输出快读加速·长整型防溢出计数统计
我不是FD26 分钟前
OpenAI vs Anthropic API 对比:流式返回 + Adapt 适配层完整方案
java·人工智能·python