问题:
难度: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;
}
}