题目描述:
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.
Example:
Input: [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
1 - 0 - 2 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
Output: 7
Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2), 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.
class Solution {
public:
int shortestDistance(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dist(m, vector<int>(n, 0)); // 表示每个空节点到所有门的最短距离之和
vector<vector<int>> moves={{-1,0}, {1,0}, {0,-1}, {0,1}};
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(grid[i][j] == 1) // 发现一扇门,就从这扇门出发,根据BFS遍历所有的空节点,保证距离最小
{
vector<vector<int>> temp=grid; // temp复制grid,0表示没有遍历过的空节点
queue<vector<int>> q;
q.push({i, j, 0});
while(q.size() > 0)
{
vector<int> p=q.front(); // 队列头元素,p[0]是横坐标,p[1]是纵坐标,p[2]表示从门到该节点的距离
q.pop();
for(auto move: moves)
{
int x=p[0]+move[0];
int y=p[1]+move[1];
if(x>=0&&x<m&&y>= 0&&y< n&&temp[x][y]==0)
{
temp[x][y]=p[2]+1;
dist[x][y]+=temp[x][y];
q.push({x, y, temp[x][y]});
}
}
}
// 对于每一扇门,如果这扇门遍历不到一个空节点,就要把它置为-1,表示它是一个达到不到的节点
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(temp[i][j] == 0) grid[i][j] = -1;
}
}
}
int result = INT_MAX;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(grid[i][j] == 0)
result = min(result, dist[i][j]);
}
}
if(result == INT_MAX) return -1;
else return result;
}
};