286. Walls and Gates

You are given an m x n grid rooms 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.

class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        if not rooms or not rooms[0]:
        m, n = len(rooms), len(rooms[0])

        gates = []
        for r in range(m):
            for c in range(n):
                if rooms[r][c] == 0:
                    gates.append((r, c))

        def neighbors(r, c):
            for nr, nc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
                if 0 <= nr < m and 0 <= nc < n and rooms[nr][nc] == 2147483647:
                    yield (nr, nc)

        queue = collections.deque(gates)
        while queue:
            r, c = queue.popleft()
            for nr, nc in neighbors(r, c):
                rooms[nr][nc] = rooms[r][c] + 1
                queue.append((nr, nc))

417. Pacific Atlantic Water Flow

There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island’s left and top edges, and the Atlantic Ocean touches the island’s right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell’s height is less than or equal to the current cell’s height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.

class Solution:
    def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
        nrow, ncol = len(matrix), len(matrix[0])

        def dfs(stack):
            reachable = set()
            while stack:
                node = stack.pop()
                r, c = node
                for nr, nc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
                    if (nr, nc) in reachable:
                    if 0 <= nr < nrow and 0 <= nc < ncol and matrix[nr][nc] >= matrix[r][c]:
                        stack.append((nr, nc))
            return reachable

        p_reachable = dfs([(r, 0) for r in range(nrow)] + [(0, c) for c in range(ncol)])
        a_reachable = dfs([(r, ncol - 1) for r in range(nrow)] + [(nrow - 1, c) for c in range(ncol)])

        reachable = p_reachable.intersection(a_reachable)
        return reachable