DSA Factory
Free Graphs lessonsGraphs · Stage 9 · Mastery · Step 2

Rain on a hill

Count the cells where rain could run down to both coasts, by working backwards uphill from each coast. About 14 minutes.

Search backwards

A rectangular island has heights. Rain flows from a cell to a neighbour that is the same height or lower. The top and left edges touch the first coast, and the bottom and right edges touch the second. Which cells can send rain to both?

Asking it forwards from every cell means a search per cell. Flip it around. Start at the first coast's edge cells and walk uphill, to neighbours that are the same height or higher: every cell you reach can send water to that coast. Do the same from the second coast, and count the cells in both results.

Reverse the move: water goes down, so search goes up.
Two searches: one per coast, then intersect.
Heights. Which cells can reach both coasts (top-left edges and bottom-right edges)?
012
0
1
2
2
1
3
2
3
2
2
4
5
first_coast
9

Climb from the top and left edges. Every one of the 9 cells can send rain to the first coast.

Move 1 of 3
Quick check

Why climb from the coast instead of simulating the rain from every cell?

  1. ATwo climbs cover all cells, instead of one search per cell
  2. BWater flows uphill
  3. CIt gives a different answer but is easier
Show the answer

Two climbs cover all cells, instead of one search per cell. Each climb visits every cell at most once.

Your problem

Rain to both coasts

heights is a grid of whole numbers giving the height of each cell. Rain on a cell flows to any neighbouring cell (up, down, left or right) whose height is the same or lower. The first coast touches the top row and the left column. The second coast touches the bottom row and the right column. Rain on a cell reaches a coast if it can flow, step by step, to a cell on that coast's edges. Return how many cells can send rain to both coasts.

Example
heights = [[1, 2, 2], [3, 2, 3], [2, 4, 5]] → 8

1 ≤ rows, columns ≤ 20 · 0 ≤ height ≤ 100

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve