leetcode994.腐烂的橘子

思路源自

【力扣hot100】【LeetCode 994】腐烂的橘子|多源BFS

这里图中的腐烂的的橘子是同时对周围进行腐化,所以采用多源bfs就能解决

多源bfs与单源bfs的区别就在于队列取出时一轮是取出队列当中的全部元素

java 复制代码
class Solution {
    public int orangesRotting(int[][] grid) {
        int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//记录四个方向
        int result=0;//记录需要的分钟数
        int fresh=0;//记录新鲜橘子的数目
        Queue<int[]> queue = new ArrayDeque<>();//队列存储腐烂橘子
        int m = grid.length, n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j]==1)
                    fresh++;
                else if(grid[i][j]==2)
                    queue.add(new int[]{i, j});
            }
        }
        while (!queue.isEmpty()) {
            int len = queue.size();
            while (len-- != 0) {
                int[] coordinate = queue.remove();
                //腐化四个方向上的新鲜橘子
                for (int[] dir : dirs) {
                    int x = coordinate[0] + dir[0];
                    int y = coordinate[1] + dir[1];
                    if(x<0||y<0||x>=m||y>=n||grid[x][y]!=1)
                        continue;
                    queue.add(new int[]{x, y});
                    grid[x][y]=2;
                    fresh--;
                }
            }
            if(!queue.isEmpty())//下一轮还有
                result++;
        }
        if(fresh>0)
            return -1;
        else
            return result;
    }
}
相关推荐
带刺的坐椅11 分钟前
Solon 整合 LiteFlow 规则引擎:概念与实战
java·solon·liteflow
wuk99831 分钟前
互联网应用主流框架整合 Spring Boot开发
java·spring boot·后端
恣艺1 小时前
LeetCode 1074:元素和为目标值的子矩阵数量
算法·leetcode·矩阵
forestsea1 小时前
Caffeine 缓存库的常用功能使用介绍
java·缓存·caffeine
技术卷1 小时前
详解力扣高频SQL50题之1084. 销售分析 III【简单】
sql·leetcode·oracle
queenlll2 小时前
P1064 [NOIP 2006 提高组] 金明的预算方案 题解
算法
辉辉健身中2 小时前
HttpServletRequest知识点
java
摸鱼仙人~2 小时前
HttpServletRequest深度解析:Java Web开发的核心组件
java·开发语言·前端
nbsaas-boot2 小时前
收银系统优惠功能架构:可扩展设计指南(含可扩展性思路与落地细节)
java·大数据·运维
你过来啊你2 小时前
Java面向对象思想解析
android·java