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;
    }
}
相关推荐
RTC老炮2 分钟前
webrtc弱网-BBRv2算法原理
网络·算法·webrtc
RTC老炮2 分钟前
webrtc弱网-BBRv1算法原理
网络·算法·webrtc
MobotStone1 小时前
我的 AI 代码清理方法论:从原型到生产,只需 5 步
算法·程序员·架构
2301_792674861 小时前
java学习day24
java
咸鱼2.08 小时前
【java入门到放弃】跨域
java·开发语言
indexsunny8 小时前
互联网大厂Java求职面试实战:微服务与Spring生态全攻略
java·数据库·spring boot·安全·微服务·面试·消息队列
沐苏瑶8 小时前
Java 搜索型数据结构全解:二叉搜索树、Map/Set 体系与哈希表
java·数据结构·算法
冬夜戏雪9 小时前
实习面经记录(十)
java·前端·javascript
skiy9 小时前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
平生不喜凡桃李9 小时前
浅谈 Linux 中 namespace 相关系统调用
java·linux·服务器