Rotting Oranges

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. 1 <= grid.length <= 10
  2. 1 <= grid[0].length <= 10
  3. grid[i][j] is only 01, or 2.

题目理解:

给定一个二维数组表示的地图,1表示的位置有一个好橘子,2表示的位置有一个坏橘子,0表示的位置没有橘子,坏橘子每一轮会将其上下左右相邻的一个好橘子变为坏橘子,问经过多少轮,所有的橘子都会变成坏橘子

解题思路:

广度优先搜索。每一次找到会变成坏橘子的橘子,并且更新整个地图,如果某一轮没有好橘子变为坏橘子,则跳出循环。如果此时地图中还有好橘子,则返回-1,否则返回轮数

class Solution {
    public int orangesRotting(int[][] grid) {
        boolean flag = true;
        int[][] dirs = new int[][]{{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
        int row = grid.length, col = grid[0].length;
        int[][] cur = grid, next;
        int count = 0;
        while(flag){
            next = new int[row][col];
            flag = false;
            for(int i = 0; i < row; i++){
                for(int j = 0; j < col; j++){
                    if(cur[i][j] == 1 && next[i][j] == 0)
                        next[i][j] = 1;
                    else if(cur[i][j] == 2){
                        next[i][j] = 2;
                        for(int[] dir : dirs){
                            int ni = i + dir[0], nj = j + dir[1];
                            if(ni > -1 && nj >-1 && ni < row && nj < col){
                                if(cur[ni][nj] == 1){
                                    next[ni][nj] = 2;
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
            cur = next;
            count++;
        }
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(cur[i][j] == 1)
                    return -1;
            }
        }
        return count - 1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值