LeetCode 994. Rotting Oranges (Java版; Easy)

welcome to my blog

LeetCode 994. Rotting Oranges (Java版; Easy)

题目描述
In a given grid, each cell can have one of three values:

the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange.  If this is impossible, return -1 instead

Example 1:

Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:

Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation:  The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:

Input: [[0,2]]
Output: 0
Explanation:  Since there are already no fresh oranges at minute 0, the answer is just 0.
 

Note:

1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] is only 0, 1, or 2
第一次做; 核心: 1)广度优先遍历, 使用队列+循环实现 2)队列中存放烂橘子 3) 当最后一个橘子被感染时, 该橘子入队, 但是在下一轮循环中不能感染任何橘子了, 也就是在下一轮循环中不会向队列中添加新元素; 所以在下一轮循环中不能执行res++操作了, 这就要求更新res的条件不仅仅是countDown==0还得满足队列不为空
//想到一道题, 原地修改矩阵的值.....hot100或者top interview中的
//BFS
class Solution {
    public int orangesRotting(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        //队列中存放烂橘子
        Queue<Cor> queue = new LinkedList<>();
        //找到所有腐烂的橘子, 入队
        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(grid[i][j]==2){
                    queue.add(new Cor(i,j));
                }
            }
        }
        //没有腐烂的橘子, 也就是队列为空, 此时如果grid中有1, 则返回-1, 如果没有1, 则返回0; 在代码最后统一处理
        // if(queue.isEmpty())
        //     return 0;

        int res = 0;
        //烂橘子的个数, 初始时是队列中元素的个数
        int count = queue.size(), countDown;
        //bfs
        while(!queue.isEmpty()){
            countDown = count;
            count = 0;
            while(countDown>0){
                Cor cur = queue.poll();
                int x,y;
                for(int[] arr : move){
                    x = cur.x + arr[0];
                    y = cur.y + arr[1];
                    if(valid(grid, x, y) && grid[x][y]==1){
                        count++;
                        grid[x][y]=2;
                        queue.add(new Cor(x, y));
                    }
                }
                countDown--;
                //核心: !queue.isEmpty(); 感染到最后一个节点时, 这个节点在下一轮循环中已经不能感染其他节点了, 也就是队列为空, 此时不再增加res
                if(countDown==0 && !queue.isEmpty()){
                    res++;
                }
            }
        }
        for(int[] arr : grid){
            for(int a : arr){
                if(a==1)
                    return -1;
            }
        }
        return res;
    }
    
    class Cor{
        int x;
        int y;
        Cor(int x, int y){
            this.x=x;
            this.y=y;
        }
    }
    
    private int[][] move = {{-1,0}, {1,0}, {0,-1},{0,1}};
    private boolean valid(int[][] grid, int i, int j){
        return i>=0 && i<grid.length && j>=0 && j<grid[0].length;
    }
}
LeetCode最优解; 1)队列的元素是int[], 不用单独创建类 2) 用一个变量记录新鲜橘子的数量, 可以起到两个重要作用, 一个是如果第一次遍历grid时,如果没有新鲜橘子则直接返回0; 另一个是最后返回时, 如果新鲜橘子数量不为0则返回-1; 3)没有单独处理最后一个感染的橘子, 会导致count比正确的值大一, 处理方法: 返回count-1即可
class Solution {
    public int orangesRotting(int[][] grid) {
        if(grid == null || grid.length == 0) return 0;
        int rows = grid.length;
        int cols = grid[0].length;
        Queue<int[]> queue = new LinkedList<>();
        int count_fresh = 0;
        //Put the position of all rotten oranges in queue
        //count the number of fresh oranges
        for(int i = 0 ; i < rows ; i++) {
            for(int j = 0 ; j < cols ; j++) {
                if(grid[i][j] == 2) {
                    queue.offer(new int[]{i , j});
                }
                else if(grid[i][j] == 1) {
                    count_fresh++;
                }
            }
        }
        //if count of fresh oranges is zero --> return 0 
        if(count_fresh == 0) return 0;
        int count = 0;
        int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
        //bfs starting from initially rotten oranges
        while(!queue.isEmpty()) {
            ++count;
            int size = queue.size();
            for(int i = 0 ; i < size ; i++) {
                int[] point = queue.poll();
                for(int dir[] : dirs) {
                    int x = point[0] + dir[0];
                    int y = point[1] + dir[1];
                    //if x or y is out of bound
                    //or the orange at (x , y) is already rotten
                    //or the cell at (x , y) is empty
                        //we do nothing
                    if(x < 0 || y < 0 || x >= rows || y >= cols || grid[x][y] == 0 || grid[x][y] == 2) continue;
                    //mark the orange at (x , y) as rotten
                    grid[x][y] = 2;
                    //put the new rotten orange at (x , y) in queue
                    queue.offer(new int[]{x , y});
                    //decrease the count of fresh oranges by 1
                    count_fresh--;
                }
            }
        }
        return count_fresh == 0 ? count-1 : -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值