Count Cells That Climb to the Global Maximum
heights is an R x C matrix of integers. From any starting cell, walk by these rules until you stop:
- Look at all 8 neighbours (orthogonal and diagonal), ignoring positions outside the matrix.
- Only neighbours strictly higher than the current cell are eligible.
- Move to the eligible neighbour with the greatest height. If several share it, choose the smallest row index, then the smallest column index.
- Stop when no neighbour is strictly higher.
Return how many starting cells end their walk on a cell holding the matrix's global maximum. Starting on a global maximum counts; if several cells share the maximum, reaching any of them counts.
[[1, 2], -> 4 (every cell climbs to 4) [3, 4]] [[5, 1, 2, 1, 5]] -> 4 (the 2 in the middle has no higher neighbour) [[1, 5, 0], [5, 0, 0], -> 4 (from (0,0) the tie between the two 5s goes to (0,1), which is stuck) [9, 0, 0]]
1 <= R, C <= 500, R * C <= 200000.
Hints
Hint 1
The walk from a cell is fully determined, so every cell has exactly one successor (or none). That makes the matrix a forest of trees pointing uphill.
Hint 2
Heights strictly increase along a walk, so there are no cycles; memoise, per cell, whether its walk reaches the maximum, and each cell is resolved once.
Hint 3
Find the global maximum first; a cell with no higher neighbour succeeds only if it holds that value.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.