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.
Examples
trapped_water([[3,3,3],[3,1,3],[3,3,3]])→2trapped_water([[3,2,3],[3,1,3],[3,3,3]])→1trapped_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