1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
func updateMatrix(mat [][]int) [][]int {
h, w := len(mat), len(mat[0])
var queue [][2]int
dirs := [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
res, visited := make([][]int, h), make([][]bool, h)
for i := 0; i < h; i++ {
res[i] = make([]int, w)
visited[i] = make([]bool, w)
for j := 0; j < w; j++ {
if mat[i][j] == 0 {
queue = append(queue, [2]int{i, j})
visited[i][j] = true
}
}
}
length := 0
for len(queue) > 0 {
cnt := len(queue)
length++
for cnt > 0 {
cur := queue[0]
queue = queue[1:]
for _, dir := range dirs {
ni, nj := cur[0]+dir[0], cur[1]+dir[1]
if 0 <= ni && ni < h && 0 <= nj && nj < w && !visited[ni][nj] {
visited[ni][nj] = true
res[ni][nj] = length
queue = append(queue, [2]int{ni, nj})
}
}
cnt--
}
}
return res
}
|