LeetCode220726_52、腐烂的橘子

在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:

值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。

返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。

示例 1:

图1 腐烂的橘子示例图 

输入:grid = [[2,1,1],[1,1,0],[0,1,1]]
输出:4

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rotting-oranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解,BFS寻找感染最短距离,记录新鲜橘子数量,用以返回判断,遍历时,一轮一轮感染,每次将一层队列内的烂橘子全部整完在进行下一轮。

class Solution{
    public int orangesRotting(int[][] grid){
        int count = 0;
        Queue<int[]> queue = new LinkedList<>();
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == 1){
                    count++;
                } else if(grid[i][j] == 2){
                    queue.offer(new int[]{i,j});
                }
            }
        }
        int round = 0;
        while(count > 0 && !queue.isEmpty()){
            round++;
            int size = queue.size();
            for(int m = 0; m < size; m++){
                int[] pos = queue.poll();
                int x = pos[0];
                int y = pos[1];
                int[] dx = {1, 0, 0, -1};
                int[] dy = {0, -1, 1, 0};
                for(int n = 0; n < 4; n++){
                    int nextx = x + dx[n];
                    int nexty = y + dy[n];
                    if(nextx >= 0 && nextx < grid.length && nexty >= 0 && nexty < grid[0].length && grid[nextx][nexty] == 1){
                        grid[nextx][nexty] = 2;
                        count--;
                        queue.offer(new int[]{nextx,nexty});
                    }
                }
            }
        }
        if(count == 0){
            return round;    
        }else{
            return -1;
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值