SDE & MLE Prep

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