Skip to content

Commit 707e803

Browse files
committed
317 Shortest Distance from All Buildings
1 parent 13860e3 commit 707e803

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

317 Shortest Distance from All Buildings.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,17 @@ def __init__(self):
1212

1313
def shortestDistance(self, grid):
1414
"""
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
1526
:type grid: List[List[int]]
1627
:rtype: int
1728
"""
@@ -72,4 +83,4 @@ def bfs(self, grid, acc, reachable, x, y):
7283
[[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],
7384
[1, 0, 0, 0, 0, 1], [0, 1, 1, 1, 1, 0]]) == 88
7485
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

Comments
 (0)