01 Matrix LeetCode solution in Python
1class Solution:2def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:3if not mat or not mat[0]:4return []56m, n = len(mat), len(mat[0])7queue = deque()8MAX_VALUE = m * n910# Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.11for i in range(m):12for j in range(n):13if mat[i][j] == 0:14queue.append((i, j))15else:16mat[i][j] = MAX_VALUE1718directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]1920while queue:21row, col = queue.popleft()22for dr, dc in directions:23r, c = row + dr, col + dc24if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:25queue.append((r, c))26mat[r][c] = mat[row][col] + 12728return mat