File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def maxDistance (self , grid ):
3
+ """
4
+ :type grid: List[List[int]]
5
+ :rtype: int
6
+ """
7
+ from collections import deque
8
+ m , n = len (grid ), len (grid [0 ])
9
+ land = []
10
+ for i in range (m ):
11
+ for j in range (n ):
12
+ if grid [i ][j ] == 1 :
13
+ land .append ((i , j ))
14
+
15
+ if not land or len (land ) == m * n :
16
+ return - 1
17
+
18
+ res = 0
19
+ dx = [1 , - 1 , 0 , 0 ]
20
+ dy = [0 , 0 , 1 , - 1 ]
21
+
22
+ queue = deque (land )
23
+ visited = set (land )
24
+ while queue :
25
+ for _ in range (len (queue )):
26
+ x0 , y0 = queue .popleft ()
27
+
28
+ for k in range (4 ):
29
+ x = x0 + dx [k ]
30
+ y = y0 + dy [k ]
31
+
32
+ if 0 <= x < m and 0 <= y < n and grid [x ][y ] == 0 and (x , y ) not in visited :
33
+ queue .append ((x , y ))
34
+ visited .add ((x , y ))
35
+ res += 1
36
+ return res - 1
37
+
38
+
You can’t perform that action at this time.
0 commit comments