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 obstacle.
- 0 - 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.
解法1:brutal force(TLE)
从每个位置出发,跟number of islands的方法一样进行BFS寻找最近的gate。但是这个题目跟number of islands不一样的地方在于,可能存在多个可能的路径,而我们要取其中最短的那个。所以对于DFS来说,算法会遍历所有的路径,在这个过程中需要keep track of最短的那个路劲。但是如果用BFS的话,我们并不需要把所有路径找一遍然后选最小的,对于这个问题,lc官方是这么描述的:Since BFS guarantees that we search all rooms of distance d before searching rooms of distance d + 1, the distance to an empty room must be the shortest. 所以这道题目BFS应该会比DFS要快,这边只展示BFS的方法,但这样brutal force的方法依然是超时的
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
def helper(i,j):
distance = [[0]*len(rooms[0]) for _ in range(len(rooms))]
q = collections.deque()
q.append((i,j))
dirs = [[0,1],[0,-1],[-1,0],[1,0]]
while q:
pos = q.popleft()
for d in dirs:
x = d