[Leetcode学习-java]Rotting Oranges(坏橙子)

问题:

难度:easy

网址链接:https://leetcode.com/problems/rotting-oranges/

说明:

这个类似于康威生命游戏,0没有东西,1好橙子,2坏橙子,每一分钟里面的坏橙子都会让上下左右橙子变坏,然后求全部变坏的时间,如果不能返回 - 1 。

相关算法:

https://blog.csdn.net/qq_28033719/article/details/105637889 Conway's Game of Life - Unlimited Edition(康威生命游戏)

输入案例:

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.

我的代码:

每一分钟相当于一代,所以来一个暂存上一代的数组,然后遍历判断就行了。

class Solution {
    public int orangesRotting(int[][] grid) {
        int x = grid.length;
        int y = grid[0].length;
        // 创建暂存
        int rotted[][] = new int[x][y];
        int minutes = 0;
        // 每一代是否有腐烂
        boolean rotting = true;

        while(rotting) {
            rotting = false;
            for(int i = 0;i < x;i ++) {
                for(int j = 0;j < y;j ++) {
                    if(rotted[i][j] != 2)
                        rotted[i][j] = grid[i][j];
                    if(grid[i][j] == 2) {
                        if(i + 1 < x && grid[i + 1][j] == 1) {
                            rotted[i + 1][j] = 2;rotting = true;
                        }
                        if(i - 1 >= 0 && grid[i - 1][j] == 1) {
                            rotted[i - 1][j] = 2;rotting = true;
                        }
                        if(j + 1 < y && grid[i][j + 1] == 1) {
                            rotted[i][j + 1] = 2;rotting = true;
                        }
                        if(j - 1 >= 0 && grid[i][j - 1] == 1) {
                            rotted[i][j - 1] = 2;rotting = true;
                        }
                    }
                }
            }
            if(rotting) {
                minutes ++;
                int temp[][] = grid;
                grid = rotted;
                rotted = temp;
            }
        }

        // 最后遍历是否还有好橙子
        for(int i = 0;i < x;i ++)
            for(int j = 0;j < y;j ++)
                if(grid[i][j] == 1) return -1;
        return minutes;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值