法1:BFS
深刻理解!此方法类似二叉树层次搜索!!!
Python
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
res = fresh = 0
m, n = len(grid), len(grid[0])
q = collections.deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
fresh += 1
elif grid[i][j] == 2:
q.append((i, j))
di = [1, -1, 0, 0]
dj = [0, 0, 1, -1]
while len(q) > 0 and fresh > 0:
res += 1
tmp_size = len(q)
for k in range(tmp_size):
i, j = q.popleft()
for idx in range(4):
new_i = i + di[idx]
new_j = j + dj[idx]
if (new_i < 0 or new_i >= m
or new_j < 0 or new_j >= n
or grid[new_i][new_j] != 1):
continue
else:
grid[new_i][new_j] = 2
fresh -= 1
q.append((new_i, new_j))
return -1 if fresh > 0 else res
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;
}
}