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.
题解:好题。从终点(楼处)搜,进行N次BFS。注意不是同时搜,同时搜相遇停止的做法有问题!
class Solution {
public:
bool BFS(vector<vector<int>>& grid, int a, int b, int m, int n, vector<vector<int>>& values, vector<vector<int>>& nums, vector<pair<int, int>>& buildings){
queue<pair<int, int>> track;
vector<vector<bool>> visited(m, vector<bool>(n, 0));
int depth = 0;
track.push(make_pair(a, b));
while(!track.empty()){
int size = track.size();
for (int k = 0; k < size; k++){
pair<int, int> currPoint = track.front();
track.pop();
int i = currPoint.first;
int j = currPoint.second;
values[i][j] = values[i][j] == INT_MAX ? depth : values[i][j] + depth;
nums[i][j]++;
if (i - 1 >= 0 && !visited[i-1][j]) {
visited[i-1][j] = 1;
if (grid[i-1][j] == 0) track.push(make_pair(i-1, j));
}
if (i + 1 < m && !visited[i+1][j]) {
visited[i+1][j] = 1;
if (grid[i+1][j] == 0) track.push(make_pair(i+1, j));
}
if (j - 1 >= 0 && !visited[i][j-1]) {
visited[i][j-1] = 1;
if (grid[i][j-1] == 0) track.push(make_pair(i, j - 1));
}
if (j + 1 < n && !visited[i][j+1]) {
visited[i][j+1] = 1;
if (grid[i][j+1] == 0) track.push(make_pair(i, j + 1));
}
}
depth++;
}
for (int i = 0; i < buildings.size(); i++){
if (!visited[buildings[i].first][buildings[i].second])
return false;
}
return true;
}
int shortestDistance(vector<vector<int>>& grid) {
int m = grid.size();
if (m == 0) return -1;
int n = grid[0].size();
if (n == 0) return -1;
int minDis = INT_MAX;
vector<pair<int, int>> buildings;
vector<vector<int>> values(m, vector<int>(n, INT_MAX));
vector<vector<int>> nums(m, vector<int>(n, 0));
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (grid[i][j] == 1)
buildings.push_back(make_pair(i, j));
}
}
for (int i = 0; i < buildings.size(); i++){
if (!BFS(grid, buildings[i].first, buildings[i].second, m, n, values, nums, buildings))
return -1;
}
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (grid[i][j] == 0 && nums[i][j] == buildings.size()){
minDis = values[i][j] > minDis ? minDis : values[i][j];
}
}
}
return minDis == INT_MAX ? -1 : minDis;
}
};