腐烂的橘子
在给定的 m x n
网格 grid
中,每个单元格可以有以下三个值之一:
- 值
0
代表空单元格; - 值
1
代表新鲜橘子; - 值
2
代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。
返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1
。
示例 1:
输入:grid = [[2,1,1],[1,1,0],[0,1,1]]
输出:4
示例 2:
输入:grid = [[2,1,1],[0,1,1],[1,0,1]]
输出:-1
解释:左下角的橘子(第 2 行, 第 0 列)永远不会腐烂,因为腐烂只会发生在 4 个方向上。
示例 3:
输入:grid = [[0,2]]
输出:0
解释:因为 0 分钟时已经没有新鲜橘子了,所以答案就是 0 。
题解:
没有技巧,纯 BFS
func orangesRotting(grid [][]int) int {
m, n := len(grid), len(grid[0])
dirs := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
queue := []int{}
depth := make(map[int]int)
ans, cnt := 0, 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 2 {
queue = append(queue, i*n+j)
depth[i*n+j] = 0
} else if grid[i][j] == 1 {
cnt++
}
}
}
for len(queue) != 0 {
orange := queue[0]
queue = queue[1:]
x, y := orange/n, orange%n
for _, dir := range dirs {
next_x, next_y := x+dir[0], y+dir[1]
if next_x < m && next_x >= 0 && next_y < n && next_y >= 0 {
if grid[next_x][next_y] == 1 {
grid[next_x][next_y] = 2
cnt--
queue = append(queue, next_x*n+next_y)
depth[next_x*n+next_y] = depth[orange] + 1
ans = depth[next_x*n+next_y]
}
}
}
}
if cnt > 0 {
return -1
}
return ans
}