286. Walls and Gates
问题描述:
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 value231 - 1 = 2147483647
to representINF
as you may assume that the distance to a gate is less than2147483647
.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF
.
Example:
Given the 2D grid:
INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF
After running your function, the 2D grid should be:
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4
解题思路:
这道题实际上是求最短路径,我们可以用BFS来解。(DFS也可以解)
用BFS的话就是使用队列来存储可更新点的位置。
为了更新距离,我们用一个计数器cnt来记录当前距离的点的个数,每访问一个,计数器减1。
对于访问的每一个点,我们要把可更新的(矩阵中数字大于当前距离的)压入队列并且更新下一个距离的点的个数计数器nextCnt
当计数器cnt为0时,说明当前距离的点全部访问更新完了,我们需要对距离自增1,并且将nextCnt 赋给 cnt 并且将其置0.
代码:
class Solution { public: void wallsAndGates(vector<vector<int>>& rooms) { if(rooms.empty() || rooms[0].empty()) return; for(int i = 0; i < rooms.size(); i++){ for(int j = 0; j < rooms[i].size(); j++){ if(rooms[i][j] == 0) bfs(rooms, i, j); } } } private: void bfs(vector<vector<int>> &room, int i, int j){ queue<pair<int,int>> q; q.push({i,j}); int cnt = 1; int dis = 1; int nextCnt = 0; while(!q.empty()){ pair<int,int> p = q.front(); q.pop(); cnt--; if(p.first - 1 >= 0 && room[p.first-1][p.second] > dis){ room[p.first-1][p.second] = dis; q.push({p.first-1, p.second}); nextCnt++; } if(p.second - 1 >= 0 && room[p.first][p.second-1] > dis){ room[p.first][p.second-1] = dis; q.push({p.first, p.second-1}); nextCnt++; } if(p.first + 1< room.size() && room[p.first+1][p.second] > dis){ room[p.first+1][p.second] = dis; q.push({p.first+1, p.second}); nextCnt++; } if(p.second + 1 < room[0].size() && room[p.first][p.second+1] > dis){ room[p.first][p.second+1] = dis; q.push({p.first, p.second+1}); nextCnt++; } if(cnt == 0){ dis++; cnt = nextCnt; nextCnt = 0; } } } };