Walls and Gates
Total Accepted: 411
Total Submissions: 1365
Difficulty: Medium
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
.
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 -10 -1 3 4
两种思路:1.深搜,记忆化搜索。 2. 广搜,每次从门处搜(https://segmentfault.com/a/1190000003906674)
const int INF=2<<31-1; class Solution { public: int m,n; void wallsAndGates(vector<vector<int>>& grid) { m=grid.size(); if(m==0) return; n=grid[0].size(); vector<vector<bool>> vis(m,vector<bool>(n,true)); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(vis[i][j]&&grid[i][j]==INF) { dfs(i,j,grid,vis); } } } } int dfs(int x,int y,vector<vector<int>>& grid,vector<vector<bool>>& vis) { vis[x][y]=false; if(grid[x][y]>=0) return grid[x][y]; //说明该点已计算过,直接返回结果 int u,d,l,r; u=d=l=r=INF; if(x-1>=0) { if(vis[x-1][y]&&grid[x-1][y]!=-1) u=dfs(x-1,y,grid,vis); } if(x+1<m) { if(vis[x+1][y]&&grid[x+1][y]!=-1) d=dfs(x+1,y,grid,vis); } if(y-1>=0) { if(vis[x][y-1]&&grid[x][y-1]!=-1) l=dfs(x,y-1,grid,vis); } if(y+1<n) { if(vis[x][y+1]&&grid[x][y+1]!=-1) r=dfs(x,y+1,grid,vis); } grid[x][y]=min(min(min(u,d),l),r); if(grid[x][y]!=INF) grid[x][y]+=1; } };