01 Matrix LeetCode solution in Python

1
class Solution:
2
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
3
if not mat or not mat[0]:
4
return []
5

6
m, n = len(mat), len(mat[0])
7
queue = deque()
8
MAX_VALUE = m * n
9

10
# Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.
11
for i in range(m):
12
for j in range(n):
13
if mat[i][j] == 0:
14
queue.append((i, j))
15
else:
16
mat[i][j] = MAX_VALUE
17

18
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
19

20
while queue:
21
row, col = queue.popleft()
22
for dr, dc in directions:
23
r, c = row + dr, col + dc
24
if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:
25
queue.append((r, c))
26
mat[r][c] = mat[row][col] + 1
27

28
return mat

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0