SDE & MLE Prep

417. Pacific Atlantic Water Flow

Problem

heights is an island's height map. The Pacific touches its top and left edges, the Atlantic its bottom and right edges. Rain flows from a cell to a neighbour (up, down, left, right) of equal or lower height, and from edge cells into the adjacent ocean. Return every cell from which water can reach both oceans.

Example: [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] → [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

Constraints: up to 200 × 200.

Reverse the flow: from each ocean's border, walk uphill (to neighbours ≥ current). Cells reachable from both oceans are the answer.

Complexity: O(R·C).

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        R, C = len(heights), len(heights[0])

        def reach(starts):
            seen, st = set(starts), list(starts)
            while st:
                r, c = st.pop()
                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if (0 <= nr < R and 0 <= nc < C and (nr, nc) not in seen
                            and heights[nr][nc] >= heights[r][c]):
                        seen.add((nr, nc))
                        st.append((nr, nc))
            return seen

        pac = reach([(0, c) for c in range(C)] + [(r, 0) for r in range(R)])
        atl = reach([(R - 1, c) for c in range(C)] + [(r, C - 1) for r in range(R)])
        return sorted([r, c] for r, c in pac & atl)