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
}
相关推荐
露天赏雪34 分钟前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
小此方42 分钟前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
天天被压力42 分钟前
【A股分钟级高频数据完全手册 #06】北交所分钟级数据接口:京市股票Pro版最新分时
java·人工智能·python
天天被压力1 小时前
【A股分钟级高频数据完全手册 #05】指数历史分钟数据接口:Pro版沪深指数分时回放
java·人工智能·python
captain3761 小时前
▲统一功能——DispatcherServlet源码分析
java·spring·java-ee·log4j·maven
金銀銅鐵1 小时前
JDK 21 中 List.of 的实现细节:从 List12 到 ListN
java·后端·ai编程
Pniubi1 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH2 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi2 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
yeccheng3 小时前
MySQL 索引超详解:从底层 B+ 树到面试高频考点
java·开发语言·jvm·mysql·面试