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
}
相关推荐
野生技术架构师41 分钟前
金三银四面试总结篇,汇总 Java 面试突击班后的面试小册
java·面试·职场和发展
_深海凉_1 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
小袁拒绝摆烂1 小时前
多表关联大平层转JSON树形结构
java·json
ja哇2 小时前
大厂面试高频八股
java·面试·职场和发展
踩坑记录2 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎2 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰2 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx2 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
yoyo_zzm2 小时前
Laravel6.x新特性全解析
java·spring boot·后端