题干
在给定的网格中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。
返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。
示例 1:
输入:[[2,1,1],[1,1,0],[0,1,1]]
输出:4
示例 2:
输入:[[2,1,1],[0,1,1],[1,0,1]]
输出:-1
解释:左下角的橘子(第 2 行, 第 0 列)永远不会腐烂,因为腐烂只会发生在 4 个正向上。
示例 3:
输入:[[0,2]]
输出:0
解释:因为 0 分钟时已经没有新鲜橘子了,所以答案就是 0 。
提示:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] 仅为 0、1 或 2
想法
先遍历一遍
用count记录原本是新鲜的🍊的个数
同时将已经腐烂的🍊入队列
遍历完了以后再将🍊出队列,每一个🍊都要判断它上下左右是不是有新鲜橘子
如果是 那就将它腐烂并且放入队列
同时时间++
count–;
直到最后队列为空时判断count是否等于0;
若是就返回时间
否则返回-1;
Java代码
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class OrangesRotting {
//pos记录这个橘子的位置和时间
class Pos {
int x, y, time;
public Pos(int x, int y, int time) {
this.x = x;
this.y = y;
this.time = time;
}
}
public int orangesRotting(int[][] grid) {
//行
int r = grid.length;
//列
int c = grid[0].length;
//时间
int time = 0;
//待腐烂🍊个数
int count = 0;
//便于方向
int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
//队列存橘子位置
Queue<Pos> queue = new LinkedList<>();
//得到count和坏橘子放入队列
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (grid[i][j] == 1) {
count++;
}
if (grid[i][j] == 2) {
queue.add(new Pos(i, j, time));
}
}
}
//出队列
while (!queue.isEmpty()) {
Pos pos = queue.poll();
time = pos.time;
for (int k = 0; k < 4; k++) { //一个腐烂,四周受害
int newX = pos.x + direction[k][0];
int newY = pos.y + direction[k][1];
if (newX >= 0 && newX < r && newY >= 0 && newY < c && grid[newX][newY] == 1) {
grid[newX][newY] = 2; //标记腐烂
count--;
queue.add(new Pos(newX, newY, pos.time + 1)); //腐烂周期+1
}
}
}
if (count == 0) {
//都腐烂
return time;
} else {
return -1;
}
}
public void printt(int[][] test, OrangesRotting orangesRotting) {
System.out.println("矩阵为:");
int minute = orangesRotting.orangesRotting(test);
for (int i = 0; i < test.length; i++) {
System.out.println(Arrays.toString(test[i]));
}
if (minute == -1) {
System.out.println("该矩阵有橘子永不腐烂");
} else {
System.out.println("该矩阵腐烂最短时间是" + minute);
}
}
public static void main(String[] args) {
OrangesRotting orangesRotting = new OrangesRotting();
int[][] test1 = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};
int[][] test2 = {{2, 1, 1}, {0, 1, 1}, {1, 0, 1}};
int[][] test3 = {{0, 2}};
//System.out.println("该矩阵腐烂最短时间是" + orangesRotting.orangesRotting(test1));
orangesRotting.printt(test1, orangesRotting);
orangesRotting.printt(test2, orangesRotting);
orangesRotting.printt(test3,orangesRotting);
}
}