法1:BFS
深刻理解!此方法类似二叉树层次搜索!!!
Python
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
fresh = 0
queue = collections.deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
fresh += 1
elif grid[i][j] == 2:
queue.append([i, j])
res = 0
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
while queue and fresh > 0:
tmp_size = len(queue)
res += 1
for _ in range(tmp_size):
[x, y] = queue.popleft()
for i in range(4):
newX = x + dx[i]
newY = y + dy[i]
if (0 <= newX < m and 0 <= newY < n and grid[newX][newY] == 1):
grid[newX][newY] = 2
fresh -= 1
queue.append([newX, newY])
return res if fresh == 0 else -1
Java
此方法类似二叉树层次搜索。
class Solution {
public int orangesRotting(int[][] grid) {
int[] dx = {-1, 1, 0, 0}; // 方向数组
int[] dy = {0, 0, -1, 1};
Queue<int[]> queue = new LinkedList<>();
int m = grid.length, n = grid[0].length, res = 0, flash = 0;
int[][] copyGrid = new int[m][n]; // 复制,保证不改变原始输入数组
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
copyGrid[i][j] = grid[i][j];
if (grid[i][j] == 1) {
++flash;
} else if (grid[i][j] == 2) {
queue.offer(new int[]{i, j});
}
}
}
while (flash > 0 && !queue.isEmpty()) {
++res;
int tmpSize = queue.size();
for (int i = 0; i < tmpSize; ++i) {
int[] loc = queue.poll();
int x = loc[0], y = loc[1];
for (int k = 0; k < 4; ++k) {
int newX = x + dx[k];
int newY = y + dy[k];
if ((newX >= 0 && newX < m)
&& (newY >= 0 && newY < n)
&& copyGrid[newX][newY] == 1) {
copyGrid[newX][newY] = 2;
queue.offer(new int[]{newX, newY});
--flash;
}
}
}
}
if (flash > 0) {
return -1;
}
return res;
}
}
版本2,code
class Solution {
public int orangesRotting(int[][] grid) {
int ans = 0, flash = 0, m = grid.length, n = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
++flash;
} else if (grid[i][j] == 2) {
queue.offer(new int[]{i, j});
}
}
}
while (flash > 0 && !queue.isEmpty()) {
++ans;
int size = queue.size();
for (int i = 0; i < size; ++i) {
int[] loc = queue.poll();
int x = loc[0], y = loc[1];
if (x - 1 >= 0) {
if (grid[x - 1][y] == 1) {
grid[x - 1][y] = 2;
--flash;
queue.offer(new int[]{x - 1, y});
}
}
if (x + 1 < m) {
if (grid[x + 1][y] == 1) {
grid[x + 1][y] = 2;
--flash;
queue.offer(new int[]{x + 1, y});
}
}
if (y - 1 >= 0) {
if (grid[x][y - 1] == 1) {
grid[x][y - 1] = 2;
--flash;
queue.offer(new int[]{x, y - 1});
}
}
if (y + 1 < n) {
if (grid[x][y + 1] == 1) {
grid[x][y + 1] = 2;
--flash;
queue.offer(new int[]{x, y + 1});
}
}
}
}
return flash > 0 ? -1 : ans;
}
}
文章介绍了两种方法解决关于二维网格中橘子腐烂问题的算法,使用BFS遍历寻找并更新相邻未腐烂橘子的状态,直至所有可腐烂橘子变为不可腐烂。
1048

被折叠的 条评论
为什么被折叠?



