You are given a m x n 2D grid initialized with these three possible values.

  1. -1 - A wall or an obstacle.
  2. 0 - A gate.
  3. 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

这道题类似一种迷宫问题,规定了 -1 表示墙,0表示门,让求每个点到门的最近的曼哈顿距离,这其实类似于求距离场 Distance Map 的问题,那么先考虑用 DFS 来解,思路是,搜索0的位置,每找到一个0,以其周围四个相邻点为起点,开始 DFS 遍历,并带入深度值1,如果遇到的值大于当前深度值,将位置值赋为当前深度值,并对当前点的四个相邻点开始DFS遍历,注意此时深度值需要加1,这样遍历完成后,所有的位置就被正确地更新了,参见代码如下:

解法一:

class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
for (int i = ; i < rooms.size(); ++i) {
for (int j = ; j < rooms[i].size(); ++j) {
if (rooms[i][j] == ) dfs(rooms, i, j, );
}
}
}
void dfs(vector<vector<int>>& rooms, int i, int j, int val) {
if (i < || i >= rooms.size() || j < || j >= rooms[i].size() || rooms[i][j] < val) return;
rooms[i][j] = val;
dfs(rooms, i + , j, val + );
dfs(rooms, i - , j, val + );
dfs(rooms, i, j + , val + );
dfs(rooms, i, j - , val + );
}
};

那么下面再来看 BFS 的解法,需要借助 queue,首先把门的位置都排入 queue 中,然后开始循环,对于门位置的四个相邻点,判断其是否在矩阵范围内,并且位置值是否大于上一位置的值加1,如果满足这些条件,将当前位置赋为上一位置加1,并将次位置排入 queue 中,这样等 queue 中的元素遍历完了,所有位置的值就被正确地更新了,参见代码如下:

解法二:

class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
queue<pair<int, int>> q;
vector<vector<int>> dirs{{, -}, {-, }, {, }, {, }};
for (int i = ; i < rooms.size(); ++i) {
for (int j = ; j < rooms[i].size(); ++j) {
if (rooms[i][j] == ) q.push({i, j});
}
}
while (!q.empty()) {
int i = q.front().first, j = q.front().second; q.pop();
for (int k = ; k < dirs.size(); ++k) {
int x = i + dirs[k][], y = j + dirs[k][];
if (x < || x >= rooms.size() || y < || y >= rooms[].size() || rooms[x][y] < rooms[i][j] + ) continue;
rooms[x][y] = rooms[i][j] + ;
q.push({x, y});
}
}
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/286

类似题目:

Surrounded Regions

Number of Islands

Shortest Distance from All Buildings

Robot Room Cleaner

Rotting Oranges

参考资料:

https://leetcode.com/problems/walls-and-gates/

https://leetcode.com/problems/walls-and-gates/discuss/72745/Java-BFS-Solution-O(mn)-Time

https://leetcode.com/problems/walls-and-gates/discuss/72746/My-short-java-solution-very-easy-to-understand

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Walls and Gates 墙和门的更多相关文章

  1. [LeetCode] 286. Walls and Gates 墙和门

    You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstac ...

  2. LeetCode Walls and Gates

    原题链接在这里:https://leetcode.com/problems/walls-and-gates/ 题目: You are given a m x n 2D grid initialized ...

  3. leetcode 542. 01 Matrix 、663. Walls and Gates(lintcode) 、773. Sliding Puzzle 、803. Shortest Distance from All Buildings

    542. 01 Matrix https://www.cnblogs.com/grandyang/p/6602288.html 将所有的1置为INT_MAX,然后用所有的0去更新原本位置为1的值. 最 ...

  4. [Locked] Walls and Gates

    Walls and Gates You are given a m x n 2D grid initialized with these three possible values. -1 - A w ...

  5. [Swift]LeetCode286. 墙和门 $ Walls and Gates

    You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstac ...

  6. 【LeetCode】286. Walls and Gates 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 日期 题目地址:https://leetcod ...

  7. LeetCode 286. Walls and Gates

    原题链接在这里:https://leetcode.com/problems/walls-and-gates/ 题目: You are given a m x n 2D grid initialized ...

  8. Walls and Gates -- LeetCode

    You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstac ...

  9. 286. Walls and Gates

    题目: You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an ob ...

随机推荐

  1. C#基础回顾(一)—C#访问修饰符

    一.写在前面的话 好久没有停下来总结自己,转眼间15年过去好些天,回首过去的日子,亦或失去,亦或所得!生活的节奏,常常让我们带着急急忙忙的节奏去追赶,也许这并不是每个人所期望的生活方式!于他人,于自己 ...

  2. heart

    好久没写博客了,不想废话,直接欣赏效果! 点击这里,查看完美效果! 附完整代码: <!doctype html> <html> <head> <meta ch ...

  3. ASP.NET Core 中文文档 第三章 原理(8)日志

    原文:Logging 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:何镇汐.许登洋(Seay) ASP.NET Core 内建支持日志,也允许开发人员轻松切换为他们想用的其他日 ...

  4. JavaWeb——tomcat安装及目录介绍

    一.web web可以说,就是一套 请求->处理->响应 的流程.客户端使用浏览器(IE.FireFox等),通过网络(Network)连接到服务器上,使用HTTP协议发起请求(Reque ...

  5. C#中怎样实现序列化和反序列化

    我们想要将数据进行持久化的操作的话,也就是将数据写入到文件中,我们在C#中可以通过IO流来操作,同时也可以通过序列化来操作,本人是比较推荐使用序列化操作的 因为我们如果想要将一个对象持久化到文件中 如 ...

  6. 以ZeroMQ谈消息中间件的设计【译文】

    本文主要是探究学习比较流行的一款消息层是如何设计与实现的 ØMQ是一种消息传递系统,或者乐意的话可以称它为"面向消息的中间件".它在金融服务,游戏开发,嵌入式系统,学术研究和航空航 ...

  7. [转载]C#委托和事件(Delegate、Event、EventHandler、EventArgs)

    原文链接:http://blog.csdn.net/zwj7612356/article/details/8272520 14.1.委托 当要把方法作为实参传送给其他方法的形参时,形参需要使用委托.委 ...

  8. 【JS基础】算法

    Math 对象 Math.sqrt() //返回一个数的平方根

  9. Access提示“操作必须使用一个可更新的查询”的解决办法

    问题:软件工程师开发了一个asp.net+access网站,本地调试增.删.改和查都没有异常.部署到服务器windows2008 R2的IIS上运行后,查询没有异常.可是在修改操作提交时,产生异常:提 ...

  10. Position属性四个值:static、fixed、relative、absolute的区别和用法

    1.static(静态定位):默认值.没有定位,元素出现在正常的文档流中(如果设置 top, bottom, left, right, z-index这些属性就不起做作了). 2.relative(相 ...