题目
在给定的网格中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。
返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。
解题思路
BFS。先把所有腐烂的柿子入队,再利用层序遍历,遇到新鲜柿子就更新其对应的腐烂的时间状态,直到队列为空,其中柿子的腐烂的时间直接在 grid
数组更新。最后再判断 grid
中有无新鲜柿子,最后找到最长时间 -2
即可。
代码
class gridNode {
int Raw, Col, state;
public gridNode() {
}
public gridNode(int raw, int col, int state) {
Raw = raw;
Col = col;
this.state = state;
}
}
class Solution {
public static final int[][] turn = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int orangesRotting(int[][] grid) {
return bfs(grid);
}
private int bfs(int[][] grid) {
Queue<gridNode> queue = new ArrayDeque<>();
int lengthRaw = grid.length, lengthCol = grid[0].length;
for (int i = 0; i < lengthRaw; i++) {
for (int j = 0; j < lengthCol; j++) {
if (grid[i][j] == 2) queue.add(new gridNode(i, j, 2));
}
}
while (!queue.isEmpty()) {
gridNode nowNode = queue.poll();
for (int i = 0; i < 4; i++) {
gridNode nextNode = new gridNode();
nextNode.Raw = nowNode.Raw + turn[i][0];
nextNode.Col = nowNode.Col + turn[i][1];
if (judge(nextNode, lengthRaw, lengthCol)) continue;
if (grid[nextNode.Raw][nextNode.Col] == 1) {
nextNode.state = nowNode.state + 1;
grid[nextNode.Raw][nextNode.Col] = nextNode.state;
queue.add(nextNode);
}
}
}
int ans = 0;
for (int i = 0; i < lengthRaw; i++) {
for (int j = 0; j < lengthCol; j++) {
if (grid[i][j] == 1) return -1;
ans = Math.max(ans, grid[i][j]);
}
}
return ans >= 2 ? ans - 2 : ans;
}
private boolean judge(gridNode nextNode, int lengthRaw, int lengthCol) {
if (nextNode.Raw < 0 || nextNode.Raw >= lengthRaw || nextNode.Col < 0 || nextNode.Col >= lengthCol) return true;
else return false;
}
}
本铸币脑子没判一开始就没有柿子的情况(摸了