
public class Solution {
public class Orange {// 橘子
int x, y;// 横坐标,纵坐标
public Orange(int x, int y) {
this.x = x;
this.y = y;
}
}
public int orangesRotting(int[][] grid) {
Queue<Orange> queue = new LinkedList<Orange>();
Queue<Orange> queue1 = new LinkedList<Orange>();
int level = 0;
int visited[][] = new int[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 2) {// 腐烂的
visited[i][j] = 2;// 腐烂的
queue.add(new Orange(i, j));
} else if(grid[i][j] == 0) {// 空的
visited[i][j] = 0;// 空的
} else {
visited[i][j] = 1;// 新鲜的
}
}
}
while (!queue.isEmpty()) {
int x = queue.peek().x;
int y = queue.poll().y;
if (x - 1 > -1 && visited[x - 1][y] == 1) {
visited[x - 1][y] = 2;
queue1.add(new Orange(x - 1, y));
}
if (y - 1 > -1 && visited[x][y - 1] == 1) {
visited[x][y - 1] = 2;
queue1.add(new Orange(x, y - 1));
}
if (x + 1 < grid.length && visited[x + 1][y] == 1) {
visited[x + 1][y] = 2;
queue1.add(new Orange(x + 1, y));
}
if (y + 1 < grid[0].length && visited[x][y + 1] == 1) {
visited[x][y + 1] = 2;
queue1.add(new Orange(x, y + 1));
}
if (queue.isEmpty()) {
if (!queue1.isEmpty()) {
while (!queue1.isEmpty()) {
queue.add(queue1.poll());
}
level += 1;
}
}
}
for (int i = 0; i < visited.length; i++) {
for (int j = 0; j < visited[i].length; j++) {
if (visited[i][j] == 1) {
return -1;
}
}
}
return level;
}
}
#华为od#