Find all cells reachable by downhill flow
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: 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.
Constraints
- 0 <= sr < m, 0 <= sc < n
- Heights are arbitrary integers (may be negative, may repeat).
- Water flows only to a strictly lower neighbor (equal heights do not flow).
- The start cell is always wet.
- m, n can be up to a few thousand; target near-linear time.
Examples
Input: ([[5,4,3],[6,1,2],[7,8,9]], (0,0))
Expected Output: [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2]]
Explanation: From (0,0)=5: right to 4 then 3; down-diagonally water reaches 1 at (1,1) via 4->1, and 2 at (1,2) via 3->2. The 6/7/8/9 block (all >= current) are never lower, so the bottom-left and corner stay dry.
Input: ([[1,2,3],[8,9,4],[7,6,5]], (1,1))
Expected Output: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
Explanation: Start at the peak 9 in the center. Every other cell is reachable by a strictly-decreasing path spiraling outward (9->8->7->...->1 and 9->4->3->2->1, etc.), so the entire grid becomes wet.
Input: ([[5]], (0,0))
Expected Output: [[0, 0]]
Explanation: A single cell; only the start is wet.
Input: ([[3,3,3],[3,3,3],[3,3,3]], (1,1))
Expected Output: [[1, 1]]
Explanation: All heights equal. Since flow requires a strictly lower neighbor, water never leaves the start cell.
Input: ([[9,8,7,6,5]], (0,0))
Expected Output: [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]]
Explanation: A single monotonically decreasing row; water flows all the way to the right, wetting every cell.
Input: ([[10,1],[2,3]], (0,0))
Expected Output: [[0, 0], [0, 1], [1, 0]]
Explanation: From 10, water reaches 1 (right) and 2 (down). The cell 3 at (1,1) is higher than both 1 and 2, so it is never reached and stays dry.
Input: ([[-1,-2,-3],[-4,-5,-6]], (0,0))
Expected Output: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]
Explanation: Negative heights work the same way: -1 > -2 > -3 and -4 > -5 > -6 with each top cell above the one below, so flow reaches every cell.
Hints
- This is a directed flood-fill: from each cell you may only move to a strictly-lower 4-directional neighbor. Because every move strictly decreases height, you can never revisit a cell, so a single BFS or DFS from the start visits each reachable cell exactly once.
- Equal heights block flow (the rule is strictly lower). Mark cells visited when you enqueue them to avoid duplicates, and collect every dequeued cell as wet.