- Walls and Gates
中文English
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 2^31 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a Gate, that room should remain filled with INF
Example
Example1
Input:
[[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Output:
[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Explanation:
the 2D grid is:
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
the answer is:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
Example2
Input:
[[0,-1],[2147483647,2147483647]]
Output:
[[0,-1],[1,2]]
解法1:BFS
把所有的门先放入queue中,然后就跟通常的BFS一样了。
注意
1)门不一定在边界,也可能在中间。
2)我们不需要直到具体的层数,因为可以根据
rooms[newX][newY] = rooms[headNode.first][headNode.second] + 1;
先碰到先改。当room的值改了以后就不是INF,这样以后就不会再次更改了。
代码如下:
class Solution {
public:
/**
* @param rooms: m x n 2D grid
* @return: nothing
*/
void wallsAndGates(vector<vector<int>> &rooms) {
int m = rooms.size();
if (m == 0) return;
int n = rooms[0].size();
vector<int> dx = {0, 0, 1, -1};
vector<int> dy = {1, -1, 0, 0};
const int INF = 2147483647;
queue<pair<int, int>> q;
//push the doors (in the border) to the queue
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (rooms[i][j] == 0) q.push({i, j});
}
}
// for (int i = 0; i < m; ++i) {
// if (rooms[i][0] == 0) q.push({i, 0});
// if (rooms[i][n - 1] == 0) q.push({i, n - 1});
// }
// for (int i = 1; i < n - 1; ++i) {
// if (rooms[0][i] == 0) q.push({0, i});
// if (rooms[m - 1][i] == 0) q.push({m - 1, i});
// }
while(!q.empty()) {
pair<int, int> headNode = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int newX = headNode.first + dx[i];
int newY = headNode.second + dy[i];
if (newX >= 0 && newX <= m - 1 && newY >= 0 && newY <= n - 1 && rooms[newX][newY] == INF) {
q.push({newX, newY});
rooms[newX][newY] = rooms[headNode.first][headNode.second] + 1;
}
}
}
return;
}
};