Skip to content
BytePatterns

Cells Draining to Both Coasts

MediumMatrix & Grid#reverse-flood-fill#multi-source-search~30m

Problem

A height map of an island is a grid of numbers. The west coast runs along the top and left edges, and the east coast runs along the bottom and right edges. Rain on a cell flows to any sideways neighbour whose height is less than or equal to the cell's own height, and a cell on an edge drains straight into that coast. Return every cell, as [row, col] in row-major order, from which rain can reach both coasts. The grid has between 1 and 200 rows and columns, so running a separate search from every cell is too slow.

Examples

Input:  heights = [[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]]
Output: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]
Input:  heights = [[1, 2], [4, 3]]
Output: [[0, 1], [1, 0], [1, 1]]
Why:    the corner holding 1 is lower than both of its neighbours, so it only reaches the west coast
Input:  heights = [[1]]
Output: [[0, 0]]
Why:    edge case, a single cell touches both coasts

Hints

0 / 3

Stuck on the idea rather than the code? Flood Fill covers it.