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.
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.