本文已参与「新人创作礼」活动,一起开启掘金创作之路。
原文链接:blog.csdn.net/roufoo/arti…
Build Post Office II Given a 2D grid, each cell is either a wall 2, an house 1 or empty 0 (the number zero, one, two), find a place to build a post office so that the sum of the distance from the post office to all the houses is smallest.
Return the smallest sum of distance. Return -1 if it is not possible.
Example Example 1:
Input:[[0,1,0,0,0],[1,0,0,2,1],[0,1,0,0,0]] Output:8 Explanation: Placing a post office at (1,1), the distance that post office to all the house sum is smallest. Example 2:
Input:[[0,1,0],[1,0,1],[0,1,0]] Output:4 Explanation: Placing a post office at (1,1), the distance that post office to all the house sum is smallest. Challenge Solve this problem within O(n^3) time.
Notice You cannot pass through wall and house, but can pass through empty. You only build post office on an empty.
解法1:BFS 注意这题跟Build Post Office I 不一样,那道题目没有wall,并且可以穿过房屋和空地,所以肯定只要有房屋和空地就肯定有解,而这道题不能穿墙和房屋,有可能有的房屋永远到不了某个空地,所以就无解。 另外Build Post Office I可以简单的把4个方向的累加房屋数加起来,然后再根据Manhattan距离加上相应的累加距离即可。这题不能用这个方法,因为不能穿墙和房屋,所以用BFS比较好,因为BFS可以算最短距离。 房屋和墙的区别是:房屋要累加其到起始点的距离。
class Solution {
public:
/**
* @param grid: a 2D grid
* @return: An integer
*/
int shortestDistance(vector<vector<int>> &grid) {
int rowSize = grid.size();
int colSize = grid[0].size();
if (rowSize == 0 || colSize == 0) return 0;
gMinTotalLen = INT_MAX;
gTotalHouseCount = 0;
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < colSize; ++j) {
if (grid[i][j] == 1) gTotalHouseCount++;
}
}
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < colSize; ++j) {
if (grid[i][j] == 0) bfs(grid, i, j);
}
return gMinTotalLen == INT_MAX ? -1 : gMinTotalLen;
}
private:
int gMinTotalLen;
int gTotalHouseCount;
void bfs(vector<vector<int>> &grid, int x, int y) {
vector<int> dx = {1, -1, 0, 0};
vector<int> dy = {0, 0, 1, -1};
queue<pair<int, int>> q;
int rowSize = grid.size();
int colSize = grid[0].size();
vector<vector<int>> visited(rowSize, vector<int>(colSize, 0));
q.push({x, y});
visited[x][y] = 1;
int totalLen = 0;
int step = 0;
int totalHouseCount = 0;
while(!q.empty()) {
step++;
int qSize = q.size();
for (int i = 0; i < qSize; ++i) {
pair<int, int> topNode = q.front();
q.pop();
for (int j = 0; j < 4; ++j) {
int newX = topNode.first + dx[j];
int newY = topNode.second + dy[j];
if (newX >= 0 && newX < rowSize && newY >= 0 && newY < colSize && !visited[newX][newY]) {
visited[newX][newY] = 1;
if (grid[newX][newY] == 2) {
continue;
}
else if (grid[newX][newY] == 1) {
totalLen += step;
totalHouseCount++;
}
else {
q.push({newX, newY});
}
}
}
}
}
if (gTotalHouseCount == totalHouseCount) gMinTotalLen = min(gMinTotalLen, totalLen);
return;
}
};