286 Walls and Gates

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了286 Walls and Gates相关的知识,希望对你有一定的参考价值。

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

-1 - A wall or an obstacle.
- 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 -1 INF INF After running your function, the 2D grid should be: -1 0 1 2 1 -1 -1 2 -1 -1 3 4

 

实际上就是找每个房间到最近的门的距离,我们从每个门开始,广度优先搜索并记录层数就行了。如果某个房间之前被标记过距离,那就选择这个距离和当前距离中较小的那个。这题要注意剪枝,如果下一步是门或者下一步是墙或者下一步已经访问过了,就不要加入队列中。否则会超时。

以上是关于286 Walls and Gates的主要内容,如果未能解决你的问题,请参考以下文章

286. Walls and Gates

286. Walls and Gates

LeetCode 286: Walls and Gates

[LeetCode] 286. Walls and Gates 墙和门

LeetCode Walls and Gates

[Locked] Walls and Gates