Walls and Gates(反向BFS)
Question
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 231 - 1 =
2147483647to representINFas you may assume that the distance to a gate is less than2147483647Fill 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 INFAfter running your function, the 2D grid should be:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4分析
反向BFS,不用空房间做BFS,而用门开始做BFS。初始把所有门都加入Queue
rooms[nx][ny] < rooms[x][y] + 1 可以去重,不需要的就不会重复计算了。
python
不用 seen, 替代的是每次比较rooms[nx][ny] > rooms[x][y] + 1, 不行就不入Q
Last updated
Was this helpful?