- 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;
}
};
二刷:
class Solution {
public:
/**
* @param grid: a 2D grid
* @return: An integer
*/
int shortestDistance(vector<vector<int>> &grid) {
int m = grid.size();
int n = grid[0].size();
int res = INT_MAX;
countSum.resize(m, vector<int>(n, 0));
// visited.resize(m, vector<bool>(n, false));
visitedTime.resize(m, vector<int>(n, 0));
vector<pair<int, int>> houses;
vector<pair<int, int>> empties;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
empties.push_back({i,j});
} else if (grid[i][j] == 1) {
houses.push_back({i, j});
}
}
}
for (auto house : houses) {
bfs(grid, house);
}
for (auto empty : empties) {
if (visitedTime[empty.first][empty.second] != houses.size()) continue;
res = min(res, countSum[empty.first][empty.second]);
}
return res == INT_MAX ? -1 : res;
}
private:
vector<vector<int>> countSum;
vector<vector<int>> visitedTime;
void bfs(vector<vector<int>> &grid, pair<int, int> &pos) {
int m = grid.size(), n = grid[0].size();
int step = 0;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
vector<vector<bool>> visited(m, vector<bool>(n, false)); //这个必须每次bfs都清零,所以不要作为全局变量
queue<pair<int, int>> q;
q.push({pos.first, pos.second});
visited[pos.first][pos.second] = true;
while (!q.empty()) {
int qSize = q.size();
for (int i = 0; i < qSize; i++) {
auto frontNode = q.front();
q.pop();
int x = frontNode.first, y = frontNode.second;
if (grid[x][y] == 0) {countSum[x][y] += step;
}
for (int j = 0; j < 4; j++) {
int newX = x + dx[j];
int newY = y + dy[j];
if (newX >= 0 && newX < m && newY >= 0 && newY < n &&
grid[newX][newY] == 0 && !visited[newX][newY]) {
q.push({newX, newY});
visited[newX][newY] = true;
visitedTime[newX][newY]++;
}
}
}
step++;
}
return;
}
};