-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-matrix.py
29 lines (23 loc) · 1.08 KB
/
01-matrix.py
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
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
def inbound(row, col):
return row >= 0 and col >= 0 and row < len(matrix) and col < len(matrix[0])
visited = set()
queue = deque()
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] == 0:
visited.add((row, col))
queue.append((row, col))
while queue:
r, c = queue.popleft()
for x, y in [(1, 0),(0, 1),(-1, 0),(0, -1)]:
new_row = r + x
new_col = c + y
if (new_row, new_col) in visited:
continue
if inbound(new_row, new_col) and matrix[new_row][new_col] not in visited:
queue.append((new_row, new_col))
visited.add((new_row, new_col))
matrix[new_row][new_col] = matrix[r][c] + 1
return matrix