You are given an m x n
grid
where each cell can have one of three values:
0
representing an empty cell,1
representing a fresh orange, or2
representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent 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
.
Example 1:
Input: grid = [[2,1,1],[1,1,0],[0,1,1]] Output: 4
Example 2:
Input: grid = [[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: grid = [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 10
grid[i][j]
is0
,1
, or2
.
题目链接:https://leetcode.com/problems/rotting-oranges/
题目大意:有一些烂橘子,没秒会使上下左右的橘子变烂,问需要多少秒可以使所有橘子变烂,若不可能输出-1
题目分析:有点类似二叉树的分层遍历,每秒将当前的烂橘子向四个方向延伸即可,bfs完再判断是否还存在好橘子
3ms,时间击败64.85%
class Solution {
class RottenOrange {
int x, y;
RottenOrange(int x, int y) {
this.x = x;
this.y = y;
}
}
private final int[] dx = new int[] {0, 1, 0, -1};
private final int[] dy = new int[] {1, 0, -1, 0};
public int orangesRotting(int[][] grid) {
int n = grid.length, m = grid[0].length;
Queue<RottenOrange> q = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 2) {
q.offer(new RottenOrange(i, j));
}
}
}
int cnt = 0;
while (!q.isEmpty()) {
int sz = q.size();
cnt++;
for (int i = 0; i < sz; i++) {
RottenOrange ro = q.poll();
for (int j = 0; j < 4; j++) {
int nx = ro.x + dx[j];
int ny = ro.y + dy[j];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == 1) {
grid[nx][ny] = 2;
q.offer(new RottenOrange(nx, ny));
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
return -1;
}
}
}
return cnt == 0 ? 0 : cnt - 1;
}
}