@@ -12,6 +12,17 @@ def __init__(self):
12
12
13
13
def shortestDistance (self , grid ):
14
14
"""
15
+ BFS & collect all distance
16
+
17
+ ideas:
18
+ Pruning: don't use a fresh "visited" for each BFS. Instead, I walk only
19
+ onto the cells that were reachable from all previous buildings. From the
20
+ first building I only walk onto cells where grid is 0, and make them -1.
21
+ From the second building I only walk onto cells where grid is -1, and I
22
+ make them -2.
23
+ -1
24
+ -2
25
+ -3
15
26
:type grid: List[List[int]]
16
27
:rtype: int
17
28
"""
@@ -72,4 +83,4 @@ def bfs(self, grid, acc, reachable, x, y):
72
83
[[1 , 1 , 1 , 1 , 1 , 0 ], [0 , 0 , 0 , 0 , 0 , 1 ], [0 , 1 , 1 , 0 , 0 , 1 ], [1 , 0 , 0 , 1 , 0 , 1 ], [1 , 0 , 1 , 0 , 0 , 1 ],
73
84
[1 , 0 , 0 , 0 , 0 , 1 ], [0 , 1 , 1 , 1 , 1 , 0 ]]) == 88
74
85
assert Solution ().shortestDistance ([[1 , 2 , 0 ]]) == - 1
75
- assert Solution ().shortestDistance ([[1 , 0 , 2 , 0 , 1 ], [0 , 0 , 0 , 0 , 0 ], [0 , 0 , 1 , 0 , 0 ]]) == 7
86
+ assert Solution ().shortestDistance ([[1 , 0 , 2 , 0 , 1 ], [0 , 0 , 0 , 0 , 0 ], [0 , 0 , 1 , 0 , 0 ]]) == 7
0 commit comments