-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01 Matrix.py
28 lines (21 loc) · 874 Bytes
/
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
def updateMatrix(matrix):
rows, cols = len(matrix), len(matrix[0])
for row in range(rows):
for col in range(cols):
if matrix[row][col] != 0:
top = matrix[row - 1][col] if row > 0 else float('inf')
left = matrix[row][col - 1] if col > 0 else float('inf')
matrix[row][col] = min(top, left) + 1
for row in range(rows)[::-1]:
for col in range(cols)[::-1]:
if matrix[row][col] != 0:
bottom = matrix[row + 1][col] if row < rows - 1 else float('inf')
right = matrix[row][col + 1] if col < cols - 1 else float('inf')
matrix[row][col] = min(matrix[row][col], min(bottom, right) + 1)
return matrix
matrix = [[0, 0, 0],
[0, 1, 0],
[1, 1, 1]]
matrix = updateMatrix(matrix)
for row in matrix:
print(row)