一、题目描述
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.
二、题解
方法一:bfs
算法
每分钟每个腐烂的橘子(2)都会使其上下左右的新鲜橘子(1)腐烂。
- 第一个腐烂的橘子在第一个网格 (0, 0),所以只让其上下左右的新鲜橘子入队,并用 minute 标记腐烂时间,并让新鲜橘子(1)变为腐烂的橘子(2)。
- 用 minute 记录腐烂的持续时间,每一层的橘子在内一层的橘子的腐烂时间基础之上自增 1,代表时间过了 1 分钟。
- 最后检查网格中是否还有新鲜的橘子
- 有,返回 -1 代表 impossible。
- 没有则返回 minute。
static int[][] dir = { {-1,0},{1,0},{0,-1},{0,1} };
public int orangesRotting(int[][] grid) {
int R = grid.length;
int C = grid[0].length;
int minute = 0;
Queue<Pos> queue = new LinkedList<>();
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++)
if (grid[i][j] == 2)
queue.add(new Pos(i, j, minute));
}
while (!queue.isEmpty()) {
Pos pos = queue.poll();
minute = pos.minute;
for (int k = 0; k < 4; k++) {//一个腐烂,四周受害
int newX = pos.x + dir[k][0];
int newY = pos.y + dir[k][1];
boolean inArea = newX >= 0 && newX < R && newY >= 0 && newY < C;
if (inArea && grid[newX][newY] == 1) {
grid[newX][newY] = 2; //标记腐烂
queue.add(new Pos(newX, newY, pos.minute + 1)); //腐烂周期+1
}
}
}
for(int[] row : grid) {
for (int i : row)
if (i == 1) return -1;
}
return minute;
}
class Pos {
int x, y,minute;
public Pos(int _x, int _y, int _minute) {
x = _x;
y = _y;
minute = _minute;
}
}
复杂度分析
- 时间复杂度: ,大约需要遍历网格一遍。
- 空间复杂度: ,