Python coding

Rain that reaches both seas

An island is a non-empty grid heights of integers. Sea A washes its top and left edges; sea B, its bottom and right edges. Rain on a cell flows to any neighbor up, down, left or right whose height is lower than or equal to its own, and from a cell on an edge it pours into the sea on that edge. Return every cell [r, c] whose rain can reach both seas, in any order.

Besides the tests, one large input (a 40 × 40 island) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • drains_to_both([[1,2,3],[2,4,2],[3,2,1]]) → [[0,2],[1,1],[2,0]]
  • drains_to_both([[3,3,3],[3,1,3],[3,3,3]]) → [[0,0],[0,1],[0,2],[1,0],[1,2],[2,0],[2,1],[2,2]]
  • drains_to_both([[1,1],[1,1]]) → [[0,0],[0,1],[1,0],[1,1]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Following the rain from every cell repeats the same flood again and again. Turn the question around: from which cells can each sea be reached?

Hint 2

Start one traversal from all of a sea's edge cells at once and step only to neighbors that are higher or equal: water could flow from them to you.

Hint 3

Do it once per sea, each with its own visited set. The answer is the cells in both sets.

Solution and why it works
pythonO(R·C), R × C = grid size · O(R·C)
def drains_to_both(heights: list[list[int]]) -> list[list[int]]:
    rows, cols = len(heights), len(heights[0])

    def climb(edge: list[tuple[int, int]]) -> set[tuple[int, int]]:
        seen, stack = set(edge), list(edge)  # every edge cell of this sea at once
        while stack:
            r, c = stack.pop()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                inside = 0 <= nr < rows and 0 <= nc < cols
                if inside and (nr, nc) not in seen and heights[nr][nc] >= heights[r][c]:
                    seen.add((nr, nc))           # uphill: its rain can flow down to here
                    stack.append((nr, nc))
        return seen

    sea_a = climb([(0, c) for c in range(cols)] + [(r, 0) for r in range(rows)])
    sea_b = climb([(rows - 1, c) for c in range(cols)] + [(r, cols - 1) for r in range(rows)])
    return [[r, c] for r, c in sea_a & sea_b]

Rain flows downhill, so a cell reaches a sea exactly when the sea can climb back up to it: one traversal seeded with every edge cell of that sea, stepping to neighbors that are higher or equal. Two traversals, one per sea, visit each cell at most once, O(R·C), and the cells in both visited sets are the answer. The trap is flooding downhill from every cell on its own, O((R·C)²): on a gentle slope, each flood covers much of the island.