1
+ import heapq
2
+
3
+ class Solution :
4
+ def updateMatrix (self , mat : List [List [int ]]) -> List [List [int ]]:
5
+ dist = [[0 if cell == 0 else float ('inf' ) for cell in row ] for row in mat ]
6
+ heap = []
7
+ deleted = {}
8
+ m = len (mat )
9
+ n = len (mat [0 ])
10
+ for i in range (m ):
11
+ for j in range (n ):
12
+ heapq .heappush (heap , (dist [i ][j ], i , j ))
13
+ while len (heap ) > 0 :
14
+ currdist , i , j = heapq .heappop (heap )
15
+ while (currdist , i , j ) in deleted and len (heap ) > 0 :
16
+ deleted [(currdist , i , j )] -= 1
17
+ if deleted [(currdist , i , j )] == 0 :
18
+ del deleted [(currdist , i , j )]
19
+ currdist , i , j = heapq .heappop (heap )
20
+ if i > 0 and dist [i - 1 ][j ] > 1 + currdist :
21
+ deleted [(dist [i - 1 ][j ], i - 1 , j )] = deleted .get ((dist [i - 1 ][j ], i - 1 , j ), 0 ) + 1
22
+ dist [i - 1 ][j ] = 1 + currdist
23
+ heapq .heappush (heap , (1 + currdist , i - 1 , j ))
24
+ if i < m - 1 and dist [i + 1 ][j ] > 1 + currdist :
25
+ deleted [(dist [i + 1 ][j ], i + 1 , j )] = deleted .get ((dist [i + 1 ][j ], i + 1 , j ), 0 ) + 1
26
+ dist [i + 1 ][j ] = 1 + currdist
27
+ heapq .heappush (heap , (1 + currdist , i + 1 , j ))
28
+ if j > 0 and dist [i ][j - 1 ] > 1 + currdist :
29
+ deleted [(dist [i ][j - 1 ], i , j - 1 )] = deleted .get ((dist [i ][j - 1 ], i , j - 1 ), 0 ) + 1
30
+ dist [i ][j - 1 ] = 1 + currdist
31
+ heapq .heappush (heap , (1 + currdist , i , j - 1 ))
32
+ if j < n - 1 and dist [i ][j + 1 ] > 1 + currdist :
33
+ deleted [(dist [i ][j + 1 ], i , j + 1 )] = deleted .get ((dist [i ][j + 1 ], i , j + 1 ), 0 ) + 1
34
+ dist [i ][j + 1 ] = 1 + currdist
35
+ heapq .heappush (heap , (1 + currdist , i , j + 1 ))
36
+ return dist
0 commit comments