原题
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.
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
BFS. base case是当room为空时, 直接返回. 我们先找到房间里所有门的index, 将它们放入q, 然后对q遍历, 计算门周围的格子到门的距离, 然后在门的上下左右寻找空房间, 如果找到空房间, 更新空房间的值, 并将空房间的index加到q里, 以便寻找空房间四周的空房间到门的距离.
代码
class Solution:
def wallsAndGates(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: void Do not return anything, modify rooms in-place instead.
"""
# base case:
if not rooms:
return
row, col = len(rooms), len(rooms[0])
# find the index of a gate
q = [(i, j) for i in range(row) for j in range(col) if rooms[i][j] == 0]
for x, y in q:
# get the distance from a gate
distance = rooms[x][y]+1
directions = [(-1,0), (1,0), (0,-1), (0,1)]
for dx, dy in directions:
# find the INF around the gate
new_x, new_y = x+dx, y+dy
if 0 <= new_x < row and 0 <= new_y < col and rooms[new_x][new_y] == 2147483647:
# update the value
rooms[new_x][new_y] = distance
q.append((new_x, new_y))
解法2
DFS.
参考: https://leetcode.com/problems/walls-and-gates/discuss/72759/python-dfs-like-number-of-islands
遍历rooms, 如果遇到值为0的格子, 使用dfs更新网格的值. 定义dfs函数, base case是当x, y超出取值范围或者当前网格的值低于计算出的距离(此时当前网格要么是障碍物, 要么是空房间且已经找到一个离门更近的距离), 直接return. 函数的主体是对当前网格更新距离, 然后在它的前后左右四个方位继续递归.
代码
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
# base case
if not rooms: return
row, col = len(rooms), len(rooms[0])
for i in range(row):
for j in range(col):
if rooms[i][j] == 0:
self.dfs(rooms, i, j, 0)
def dfs(self, rooms, x, y, dist):
row, col = len(rooms), len(rooms[0])
if x < 0 or x >= row or y < 0 or y >= col or rooms[x][y] < dist:
return
rooms[x][y] = dist
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
self.dfs(rooms, x+dx, y+dy, dist+1)