[Leetcode 286]: Walls and Gates
来源:互联网 发布:gltools优化glsl着色器 编辑:程序博客网 时间:2024/05/22 07:49
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 INFINF INF INF -1INF -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;}};
0 0
- leetcode 286: Walls and Gates
- [Leetcode 286]: Walls and Gates
- *LeetCode-Walls and Gates
- Leetcode: Walls and Gates
- 286 Walls and Gates
- Leetcode 286.Walls and Gates
- LeetCode 286. Walls and Gates
- Leetcode 286. Walls and Gates
- LeetCode 286. Walls and Gates
- [leetcode 286] Walls and Gates---各个点到门的距离
- LeetCode 题解(259) : Walls and Gates
- [leetcode] 286. Walls and Gates 解题报告
- [Leetcode] 286. Walls and Gates 解题报告
- [LeetCode286]Walls and Gates
- Walls and Gates
- Walls and Gates
- Walls and Gates
- Walls and Gates
- html5ie兼容问题
- android安全——混淆技术小摘
- Raymarching Distance Fields
- Android 6.0 运行时权限处理完全解析
- PDE14 heat equation intuition
- [Leetcode 286]: Walls and Gates
- Andriod GridView不改变背景色实现网格线效果
- 抓交通肇事犯
- 查询出与jack互为好友的人名字
- Android OkHttp完全解析 是时候来了解OkHttp了
- javaWeb项目2webService
- Query 提交按钮置灰与恢复
- Linux 防火墙开放特定端口 (iptables)
- HTML 5 使用 JavaScript 来存储和访问数据(localStorage,sessionStorage)