You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: real_interview_questions/Google/shortest_distance_from_all_buildings.md
+80-1Lines changed: 80 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -34,7 +34,6 @@ class Solution(object):
34
34
:rtype: int
35
35
"""
36
36
n_buildings = sum(x.count(1) for x in grid)
37
-
bfs_queue = collections.deque()
38
37
result = -1
39
38
40
39
for row_index in range(0, len(grid)):
@@ -93,3 +92,83 @@ class Solution(object):
93
92
return True
94
93
return False
95
94
```
95
+
96
+
# SOLUTION
97
+
Instead of doing a BFS for all lands, we will utalize the fact that the question wants the sum of the distance as the answer. With this, we can instead BFS from each building instead. This will reduce the amount of BFS we have to perform. During each iteration of the BFS, we will use another array to store the distances of each land and how many buildings this land has been touched by a building. After all BFSes, we will look at the distance array and check for the min distance that have touched all buildings.
98
+
```
99
+
class Solution(object):
100
+
def shortestDistance(self, grid):
101
+
"""
102
+
:type grid: List[List[int]]
103
+
:rtype: int
104
+
"""
105
+
dp = [[[0,0] for _ in range(len(grid[0]))] for _ in range(len(grid))]
0 commit comments