给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:mat = [[0,0,0],[0,1,0],[0,0,0]]
输出:[[0,0,0],[0,1,0],[0,0,0]]
示例 2:
输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
输出:[[0,0,0],[0,1,0],[1,2,1]]
提示:
- m == mat.length
- n == mat[i].length
- 1 <= m, n <= 104
- 1 <= m * n <= 104
- mat[i][j] is either 0 or 1.
- mat 中至少有一个 0
bfs,从所有的0出发,遇到1就更新对应下标的最小步数.
func updateMatrix(mat [][]int) [][]int {
res := make([][]int, len(mat))
queue := [][]int{}
for i := range mat {
res[i] = make([]int, len(mat[i]))
for j, n := range mat[i] {
if n == 0 {
queue = append(queue, []int{i, j})
mat[i][j] = -1
}
}
}
step := 0
for len(queue) > 0 {
size := len(queue)
step++
for i := 0; i < size; i++ {
x,y := queue[i][0], queue[i][1]
if x-1 >= 0 && mat[x-1][y] == 1 {
mat[x-1][y] = -1
res[x-1][y] = step
queue = append(queue, []int{x-1, y})
}
if x+1 < len(mat) && mat[x+1][y] == 1 {
mat[x+1][y] = -1
res[x+1][y] = step
queue = append(queue, []int{x+1, y})
}
if y+1 < len(mat[0]) && mat[x][y+1] == 1 {
mat[x][y+1] = -1
res[x][y+1] = step
queue = append(queue, []int{x, y+1})
}
if y-1 >= 0 && mat[x][y-1] == 1 {
mat[x][y-1] = -1
res[x][y-1] = step
queue = append(queue, []int{x, y-1})
}
}
queue = queue[size:]
}
return res
}