题目链接: https://leetcode.com/problems/shortest-distance-from-all-buildings/
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:
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.
思路: 也是比较烦的一题了.
我们可以从一个建筑物出发来计算每一个空地到这个建筑物的距离, 然后设置一个数组sumDistance来累加统计从一个空地出发到其他所有建筑物的距离.即sumDistance[i][j]代表从位置grid[i][j]出发到其他建筑物的距离之和.
其中在从一个建筑出发寻找所有空地到其距离的时候, 我们使用bfs来计算, 并且可以每次访问地图的一个结点之后将其值-1, 用作标记已经访问过此结点, 也用于标记下一次可访问这个结点.这样就避免了再开一个数组来标记是否访问过.
代码如下:
class Solution { public: int shortestDistance(vector<vector<int>>& grid) { if(grid.size() ==0) return -1; vector<pair<int, int>> direction{{0,1},{0,-1},{1,0},{-1,0}}; int m = grid.size(), n = grid[0].size(), result=-1, flag=0; vector<vector<int>> sumDistance(m, vector<int>(n, 0)); for(int i = 0; i < m; i++) { for(int j =0; j< n; j++) { if(grid[i][j] == 1) { result = -1; queue<pair<int, int>> que; que.push(make_pair(i, j)); auto tem = grid; while(!que.empty()) { auto val = que.front(); que.pop(); for(auto dir:direction) { int x = val.first + dir.first, y = val.second+dir.second; if(x >=0 && x < m && y >=0 && y < n && grid[x][y]==flag) { grid[x][y]--; //因为是从一个建筑开始搜索,而建筑物的值是1, 所有和sum的值比tem要少1 tem[x][y] = tem[val.first][val.second] + 1; sumDistance[x][y] += (tem[x][y] -1); if(result < 0 || result > sumDistance[x][y]) result = sumDistance[x][y]; que.push(make_pair(x, y)); } } } flag--;//标记下一次可访问的结点 } } } return result; } };参考: https://leetcode.com/discuss/74453/36-ms-c-solution