-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0_1_Matrix.py
36 lines (25 loc) · 1011 Bytes
/
0_1_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
30
31
32
33
34
35
36
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
Q = deque()
m = len(mat)
n = len(mat[0])
dist = [[math.inf for v in range(n)] for j in range(m)]
def BFS(mat: List[List[int]]):
nonlocal dist
while Q:
i,j = Q.popleft()
nbrs = [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]
for x,y in nbrs:
if 0<=x<m and 0<=y<n:
if mat[x][y] == 0:
dist[x][y] = 0
elif dist[x][y] > dist[i][j]+1:
dist[x][y]=dist[i][j]+1
Q.append((x,y))
for i in range(m):
for j in range(n):
if mat[i][j]==0:
dist[i][j]=0
Q.append((i,j))
BFS(mat)
return dist