Find all cells reachable by downhill flow
AmazonSoftware Engineer · Technical ScreenLast updated
This question evaluates graph traversal and reachability reasoning on a 2D elevation grid, testing algorithmic problem-solving, complexity analysis, and handling of monotonic flow constraints.
Problem
You are given an m x n grid heights, where heights[r][c] is the elevation of cell (r, c).
A drop of water is placed at a starting cell start = (sr, sc). From a cell, water may flow to any of its 4-directional neighbors (up/down/left/right) only if the neighbor has strictly lower height than the current cell.
A cell is considered wet if water can reach it by repeatedly flowing according to the rule above (including the start cell).
Task
Return the list (or set) of all wet cells.
Input
heights: 2D integer array of sizem x nstart: two integers(sr, sc)with0 <= sr < m,0 <= sc < n
Output
- All coordinates
(r, c)that become wet.
Notes / Constraints
- You may return cells in any order.
- Assume
m, ncan be up to a few thousand (so your approach should be near-linear in grid size in the worst case). - Heights can be any integers (not necessarily unique).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.