542 01 Matrix
542 01 Matrix
01 Matrix 
Given an m x n binary matrix mat, return the distance of the nearest *0 for each cell*.
The distance between two cells sharing a common edge is 1.
Example 1:
1
2
3
4
**Input:** mat = [[0,0,0],[0,1,0],[0,0,0]]
**Output:** [[0,0,0],[0,1,0],[0,0,0]]
Example 2:
1
2
3
4
**Input:** mat = [[0,0,0],[0,1,0],[1,1,1]]
**Output:** [[0,0,0],[0,1,0],[1,2,1]]
Constraints:
1
2
3
4
5
6
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
There is at least one 0 in mat.
Note: This question is the same as 1765: https://leetcode.com/problems/map-of-highest-peak/
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
36
37
38
39
40
func updateMatrix(isWater [][]int) [][]int {
m, n := len(isWater), len(isWater[0])
res := make([][]int, m)
queue := [][]int{}
for i := 0; i < m; i++ {
res[i] = make([]int, n)
for j := 0; j < n; j++ {
if isWater[i][j] == 0 {
res[i][j] = 0
queue = append(queue, []int{i, j})
} else {
res[i][j] = -1
}
}
}
dirs := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
for len(queue) > 0 {
cell := queue[0]
queue = queue[1:]
i, j := cell[0], cell[1]
for _, d := range dirs {
ni, nj := i + d[0], j + d[1]
if ni >= 0 && ni < m && nj >= 0 && nj < n && res[ni][nj] == -1 {
res[ni][nj] = res[i][j] + 1
queue = append(queue, []int{ni, nj})
}
}
}
return res
}
This post is licensed under CC BY 4.0 by the author.

