Problem
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
- Each 0 marks an empty land which you can pass by freely.
- Each 1 marks a building which you cannot pass through.
- Each 2 marks an obstacle which you cannot pass through.
For example, given three buildings at (0,0)
, (0,4)
, (2,2)
,
and an obstacle at (0,2)
:
1 - 0 - 2 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0
The point (1,2)
is an ideal empty land to build a house, as the total travel distance
of 3+3+1=7 is minimal. So return 7.
Note:
There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
Solution
对于每一个building, 计算它能到达的每一个空地的距离。具体来讲用 dist
数组纪录,最后找最小的就好。
到下一个building时,上一个如果没有到达这个空地,那这个空地就不考虑了。这个用 canReach 数组实现。
class Solution {
vector<pair<int,int>> dirs = { make_pair(1,0),make_pair(-1,0),make_pair(0,1),make_pair(0,-1)} ;
void bfs( int curRow,int curCol,const vector<vector<int>>& grid,int numBuild,vector<vector<int>>& dist,vector<vector<int>>& canReach) {
const int M = grid.size(), N = grid[0].size();
queue<int> curLvl, nextLvl;
unordered_set<int> visited;
curLvl.push(curRow*N + curCol);
visited.insert(curRow*N + curCol);
int curDist = 0;
while(!curLvl.empty()) {
int curBuild = curLvl.front(); curLvl.pop();
int curRow = curBuild/N, curCol = curBuild%N;
for( int i = 0; i < dirs.size(); i++) {
int nextRow = curRow + dirs[i].first, nextCol = curCol + dirs[i].second;
int nextBuild = nextRow * N + nextCol;
if( nextRow >= 0 && nextRow < M && nextCol >= 0 && nextCol < N && visited.find(nextBuild) == visited.end() && grid[nextRow][nextCol] == 0 && canReach[nextRow][nextCol] == numBuild ) {
nextLvl.push(nextBuild);
visited.insert(nextBuild);
dist[nextRow][nextCol] += curDist + 1;
canReach[nextRow][nextCol] = numBuild + 1;
}
}
if(curLvl.empty()) {
swap(curLvl, nextLvl);
curDist++;
}
}
return;
}
public:
int shortestDistance(vector<vector<int>>& grid) {
if(grid.empty() || grid[0].empty()) return 0;
const int M = grid.size(), N = grid[0].size();
vector<vector<int>> dist( M, vector<int>(N, 0) );
vector<vector<int>> canReach( M, vector<int>(N, 0) );
int numBuild = 0;
for( int row = 0; row < M; row++ ){
for( int col = 0; col < N; col++){
if( grid[row][col] == 1 ) {
bfs(row, col, grid, numBuild++, dist, canReach );
}
}
}
int rst = INT_MAX;
for( int row = 0; row < M; row++ ){
for( int col = 0; col < N; col++){
if(canReach[row][col] == numBuild ) {
rst = min( rst, dist[row][col]);
}
}
}
return rst==INT_MAX ? -1 : rst;
}
};