Python coding

Rain trapped on a height map

heights is a grid of non-negative integers, the heights of square columns on a map. Rain falls on every cell; water flows between side-by-side cells (up, down, left, right, never diagonally) and pours off the map from any cell on its edge, so it stays only where higher ground surrounds it. Return how many units of water remain once it settles. In [[3, 3, 3], [3, 1, 3], [3, 3, 3]] the center holds 2 units; lower the cell above it to 2 and it holds only 1.

The grid has at least one row and one column, all rows of the same length. Aim for O(mn log(mn)) for m rows and n columns.

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

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

Water inside a region rises until it spills over the lowest point of the wall around it. The map's edge is the first wall: put every edge cell in a min-heap by height.

Hint 2

Pop the lowest wall cell: every other wall cell is at least as high, so an unvisited neighbor below its level fills with water up to exactly that level.

Hint 3

Then that neighbor joins the wall at max(level, its height), not its own height: that is how a basin's water level reaches cells far from the edge.

Solution and why it works
pythonO(mn log(mn)) · O(mn)
import heapq


def trapped_water(heights: list[list[int]]) -> int:
    rows, cols = len(heights), len(heights[0])
    seen = [[r in (0, rows - 1) or c in (0, cols - 1) for c in range(cols)] for r in range(rows)]
    wall = [(heights[r][c], r, c) for r in range(rows) for c in range(cols) if seen[r][c]]
    heapq.heapify(wall)                  # the boundary water must spill over: the edge first
    water = 0
    while wall:
        level, r, c = heapq.heappop(wall)          # lowest point of the boundary
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and not seen[nr][nc]:
                seen[nr][nc] = True
                water += max(0, level - heights[nr][nc])   # fills up to the spill level
                heapq.heappush(wall, (max(level, heights[nr][nc]), nr, nc))
    return water

Water rises until it spills over the lowest point of the wall around it, so flood from the outside in. The edge cells are the first wall, in a min-heap. Pop the lowest: an unvisited neighbor below it fills to exactly that level, since the rest of the wall is at least as high, and joins the wall at max(level, height). Each cell is pushed once: O(mn log(mn)). The 1-D trick, the tallest bar on each side of a row or column, fails: water escapes around corners.