Simulate pouring water onto terrain
AirbnbSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to model a fluid simulation on a grid using a deterministic rule set and efficient array traversal.
Problem Statement
You are given a 2D grid of non-negative integers terrain, where terrain[i][j] represents the height of the ground at coordinate (i, j). You are also given a coordinate (start_row, start_col) where a unit of water is poured.
Water flows according to these rules:
- Water at
(r, c)will flow to an adjacent cell (up, down, left, or right) that has a strictly lower height than the current cell. - If multiple adjacent cells are strictly lower, the water moves to the cell with the minimum height. If there is still a tie, the water moves to the cell that appears first in the order: (r+1, c), (r, c+1), (r-1, c), (r, c-1).
- If no adjacent cell is strictly lower, the water stays at
(r, c)and pools there, increasing the height of the terrain at(r, c)by 1. - Water flows off the grid if it reaches a boundary cell and its next move would be outside the
(0, 0)to(rows-1, cols-1)bounds.
Implement the function simulate_water(terrain, start_row, start_col) which returns the updated terrain grid after one unit of water has finished settling.
Constraints
terrainis an N x M grid (1 <= N, M <= 50).terrain[i][j]is between 0 and 1000.
Example 1
Input:
terrain = [[5, 4, 5], [4, 3, 4], [5, 4, 5]], start = (0, 0)
Output:
[[5, 4, 5], [4, 4, 4], [5, 4, 5]]
Explanation: Water starts at (0,0), flows to (0,1) (height 4), then to (1,1) (height 3), then gets stuck because all neighbors of (1,1) are height 4, so it adds 1 to (1,1).
Hints
Hint 1
Model the movement as a simulation loop that updates the current coordinate until the water is trapped or leaves the grid.
Hint 2
Be careful to differentiate between the original terrain height and the height modified by accumulated water.
Hint 3
Use a simple `while` loop with a break condition when the water either flows off-grid or finds a local minimum.
Follow-up questions
- What changes if multiple units of water are poured sequentially into the same starting coordinate?
- How would you optimize the simulation if the terrain grid were significantly larger (e.g., 1000x1000)?
- How would you modify the algorithm to account for water 'spilling over' edges if it exceeds a certain depth at a specific cell?
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.