317. Shortest Distance from All Buildings
Problem description:
You are given an m x n
grid grid
of values 0
, 1
, or 2
, where:
- each
0
marks an empty land that you can pass by freely, - each
1
marks a building that you cannot pass through, and - each
2
marks an obstacle that you cannot pass through.
You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right.
Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1
.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|
.
Example 1:
1 | Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] |
Example 2:
1 | Input: grid = [[1,0]] |
Example 3:
1 | Input: grid = [[1]] |
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either0
,1
, or2
.- There will be at least one building in the
grid
.
Solution:
- need to store each empty slot’s
total shortest distance
to every building
use a 2d array to store,shortDist
- need to know if an empty slot could reach every building
use a 2d array to store,hit
For every building[k]
, do BFS to search every reachable neighbor
- If neighbor is empty slot update
shortDist[i][j]
frombuilding[k]
to this empty slot(i,j)
, updatehit[i][j]
to note this empty slot is reachable by this building - If neighbor is a building, increase the
count
by 1. Because we need to know ifbuilding[k]
is able to reach every other buildings. - use
visited
array to note the neighbor we visited.
1 | class Solution: |
time complexity: $O(m^2 n^2)$, we need to find number of 1 takes $O(mn)$, in that loop, need to find number of 0 as well takes another $O(mn)$, so $O(m^2 n^2)$
space complexity: $O(m*n)$
reference:
related problem: