Walls and Gates 07/30
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 value 2^31 - 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
.Have you met this question in a real interview? Yes
Example
Given the 2D grid:
return the result:
先找到每一个0在矩阵中的位置,把他的坐标分别放进x queue,和y queue里,然后遍历这些0 上下左右每一个点的值,如果是inf的话,就把他们放进x queue和y queue里,然后只更新1,BFS 做法,逐层遍历 逐层更新
Last updated