542. 01 Matrix
Problem
For every cell of the binary matrix mat, return the distance to the nearest 0, moving up, down, left or right one step at a time. There is at least one 0.
Example: [[0,0,0],[0,1,0],[1,1,1]] → [[0,0,0],[0,1,0],[1,2,1]]
Constraints: up to 10⁴ cells.
Distance to the nearest 0 for each cell: multi-source BFS starting from all zeros (not from each 1!).
Complexity: O(R·C).
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
R, C = len(mat), len(mat[0])
dist = [[-1] * C for _ in range(R)]
q = deque()
for r in range(R):
for c in range(C):
if mat[r][c] == 0:
dist[r][c] = 0
q.append((r, c))
while q:
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
q.append((nr, nc))
return dist
assert Solution().updateMatrix([[0, 0, 0], [0, 1, 0], [1, 1, 1]]) == [[0, 0, 0], [0, 1, 0], [1, 2, 1]]
assert Solution().updateMatrix([[0], [1], [1]]) == [[0], [1], [2]]
assert Solution().updateMatrix([[1, 1, 1], [1, 1, 1], [1, 1, 0]]) == [[4, 3, 2], [3, 2, 1], [2, 1, 0]]
class Solution {
public int[][] updateMatrix(int[][] mat) {
int R = mat.length, C = mat[0].length;
int[][] dist = new int[R][C];
Deque<int[]> q = new ArrayDeque<>();
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) {
if (mat[r][c] == 0) q.add(new int[]{r, c});
else dist[r][c] = -1;
}
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!q.isEmpty()) {
int[] cur = q.poll();
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr >= 0 && nc >= 0 && nr < R && nc < C && dist[nr][nc] == -1) {
dist[nr][nc] = dist[cur[0]][cur[1]] + 1;
q.add(new int[]{nr, nc});
}
}
}
return dist;
}
}
func updateMatrix(mat [][]int) [][]int {
R, C := len(mat), len(mat[0])
dist := make([][]int, R)
q := [][2]int{}
for r := range dist {
dist[r] = make([]int, C)
for c := range dist[r] {
if mat[r][c] == 0 {
q = append(q, [2]int{r, c}) // BFS from every 0 at once
} else {
dist[r][c] = -1
}
}
}
for len(q) > 0 {
p := q[0]
q = q[1:]
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nr, nc := p[0]+d[0], p[1]+d[1]
if nr >= 0 && nr < R && nc >= 0 && nc < C && dist[nr][nc] == -1 {
dist[nr][nc] = dist[p[0]][p[1]] + 1
q = append(q, [2]int{nr, nc})
}
}
}
return dist
}