|
| 1 | +''' |
| 2 | +Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. |
| 3 | +
|
| 4 | +The distance between two adjacent cells is 1. |
| 5 | +''' |
| 6 | + |
| 7 | +class Solution: |
| 8 | + def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: |
| 9 | + DEFAULT = -1 |
| 10 | + queue = [] |
| 11 | + result = [[DEFAULT] * len(mat[0]) for _ in range(len(mat))] |
| 12 | + for r in range(len(mat)): |
| 13 | + for c in range(len(mat[0])): |
| 14 | + if mat[r][c] == 0: |
| 15 | + queue.append((r, c, 0)) # depth is 0. i.e. 0 steps to get to this 0 |
| 16 | + result[r][c] = 0 |
| 17 | + |
| 18 | + visited = set() |
| 19 | + while queue: |
| 20 | + row, col, depth = queue.pop(0) |
| 21 | + |
| 22 | + if (row, col) in visited: |
| 23 | + continue |
| 24 | + |
| 25 | + visited.add((row, col)) |
| 26 | + if result[row][col] == DEFAULT: # no other 0 has gotten here first |
| 27 | + result[row][col] = depth |
| 28 | + |
| 29 | + # if in bounds, not visited, and no result from another 0 yet |
| 30 | + if row > 0 and (row - 1, col) not in visited and result[row - 1][col] == DEFAULT: |
| 31 | + queue.append((row - 1, col, depth + 1)) |
| 32 | + if row < len(mat) - 1 and (row + 1, col) not in visited and result[row + 1][col] == DEFAULT: |
| 33 | + queue.append((row + 1, col, depth + 1)) |
| 34 | + if col > 0 and (row, col - 1) not in visited and result[row][col - 1] == DEFAULT: |
| 35 | + queue.append((row, col - 1, depth + 1)) |
| 36 | + if col < len(mat[0]) - 1 and (row, col + 1) not in visited and result[row][col + 1] == DEFAULT: |
| 37 | + queue.append((row, col + 1, depth + 1)) |
| 38 | + |
| 39 | + return result |
0 commit comments