[Leetcode 286]: Walls and Gates
2016-03-23 10:03
363 查看
Walls and Gates
Total Accepted: 411 Total Submissions: 1365 Difficulty: MediumYou 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 = 2147483647to represent
INFas 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 -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;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性