Skip to content

Commit cea859e

Browse files
Time: 131 ms (60.96%) | Memory: 19.2 MB (99.88%) - LeetSync
1 parent c1c2128 commit cea859e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

542-01-matrix/01-matrix.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from collections import deque
2+
3+
direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
4+
5+
class Solution:
6+
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
7+
q = deque([])
8+
9+
for i in range(len(mat)):
10+
for j in range(len(mat[i])):
11+
if mat[i][j] == 1:
12+
mat[i][j] = None
13+
else:
14+
q.append((i, j))
15+
16+
d = 1
17+
18+
while q:
19+
n = len(q)
20+
21+
for i in range(len(q)):
22+
x, y = q.popleft()
23+
24+
for dx, dy in direction:
25+
nx = dx + x
26+
ny = dy + y
27+
if 0 <= nx < len(mat) and 0 <= ny < len(mat[0]) and mat[nx][ny] == None:
28+
mat[nx][ny] = d
29+
q.append((nx, ny))
30+
31+
d += 1
32+
33+
return mat
34+
35+
36+
37+

0 commit comments

Comments
 (0)