Walls and Gates Problem
Description
LeetCode Problem 286.
You are given an m x n grid rooms initialized with these three possible values.
-1A wall or an obstacle.0A gate.INFInfinity means an empty room. We use the value2^31 - 1 = 2147483647to representINFas you may assume that the distance to a gate is less than2147483647.
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 1:

Input: rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Example 2:
Input: rooms = [[-1]]
Output: [[-1]]
Constraints:
m == rooms.lengthn == rooms[i].length1 <= m, n <= 250rooms[i][j]is-1,0, or2^31 - 1.
Solution
Approach: Multi-Source BFS from the Gates
Running a BFS from every empty room to find its nearest gate repeats a lot of work. Turn the problem around: start one BFS from all gates at once.
Put every gate (value 0) into the queue. Then repeatedly take a cell and look at its four neighbors. A neighbor that is still INF is an empty room nobody has reached yet: set it to the current cell's distance plus one and add it to the queue. Walls (-1), gates and rooms that already have a distance are skipped.
Because BFS expands in order of distance, all rooms at distance 1 from any gate are filled before any room at distance 2, and so on. So the first time a room is reached, it is reached from its nearest gate, and its value never needs to change. That is also why checking == INF is enough to avoid visiting a room twice. Rooms that no gate can reach are never touched and keep INF.
Complexity: O(mn) time, since each cell enters the queue at most once. O(mn) space for the queue in the worst case.
import collections
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
INF = 2**31 - 1
m, n = len(rooms), len(rooms[0])
# Multi-source BFS: start from every gate at once.
queue = collections.deque((i, j) for i in range(m) for j in range(n) if rooms[i][j] == 0)
while queue:
i, j = queue.popleft()
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
# Only empty rooms not reached yet; the first visit comes from the nearest gate.
if 0 <= x < m and 0 <= y < n and rooms[x][y] == INF:
rooms[x][y] = rooms[i][j] + 1
queue.append((x, y))