Katkat

Find all cells reachable by downhill flow

AmazonSoftware Engineer · Technical Screen

Last 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 size m x n
  • start: two integers (sr, sc) with 0 <= sr < m, 0 <= sc < n

Output

  • All coordinates (r, c) that become wet.

Notes / Constraints

  • You may return cells in any order.
  • Assume m, n can 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).