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
}
相关推荐
YXXY3135 分钟前
模拟算法的介绍
算法
happymaker062627 分钟前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
likerhood30 分钟前
Fastjson中的JSON.parseObject()详细讲解
java·json
KNeeg_33 分钟前
黑马点评完整代码(RabbitMQ优化)+简历编写+面试重点 ⭐
java·redis·后端·spring·面试·职场和发展·黑马点评
会编程的土豆39 分钟前
【数据结构与算法】空间复杂度从入门到面试:不仅会算,还要会解释
数据结构·c++·算法·面试·职场和发展
普通网友40 分钟前
《算法面试必刷:15 个高频 LeetCode 题(附代码)》
算法·leetcode·面试
_深海凉_42 分钟前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
张槊哲1 小时前
C++ 进阶指南:如何丝滑地理解与实践多线程与多进程
开发语言·c++·算法
铁皮哥1 小时前
【后端/Agent 开发】给你的项目配置一套 .claude/ 工作流:别再裸用 Claude Code 了!
java·windows·python·spring·github·maven·生活
乐之者v1 小时前
AI编程 -- codex添加代码,在intellij Idea中没有显示,如何处理?
java·ide·intellij-idea