题目链接:https://leetcode.com/problems/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 value 231 - 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, it should be filled with INF
.
For 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
思路:依然是一个DFS,遍历数组中的每一个元素,碰到原始是0的,也就是门,就以这个点开始做DFS.然后向上下左右方向走,需要注意的是为了防止循环调用,我们需要判断一下如果下一个位置的元素比当前元素小或者相等,就没有必要再去那个位置了.
代码如下:
class Solution { public: void DFS(vector<vector<int>>& rooms, int i, int j, int val) { if(i<0 || i>=rooms.size() || j<0 || j>=rooms[0].size() || rooms[i][j] == -1 || rooms[i][j]<val) return; rooms[i][j] = min(rooms[i][j], val); DFS(rooms, i, j+1, rooms[i][j]+1); DFS(rooms, i, j-1, rooms[i][j]+1); DFS(rooms, i+1, j, rooms[i][j]+1); DFS(rooms, i-1, j, rooms[i][j]+1); } void wallsAndGates(vector<vector<int>>& rooms) { if(rooms.size()==0) return; for(int i =0; i< rooms.size(); i++) for(int j =0; j< rooms[0].size(); j++) if(rooms[i][j] == 0) DFS(rooms, i, j, 0); } };