Rain Flowing to Both Seas
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
A rectangular island is divided into cells; heights[i][j] is the height of a cell. The top and left coasts
touch the North-West Sea and the bottom and right coasts touch the South-East Sea.
Rain on a cell can flow to any horizontally or vertically adjacent cell whose height is less than or equal to the current one. A cell on the border flows into the sea on that side (e.g. the top row into the North-West Sea, the rightmost column into the South-East Sea).
Return the number of cells from which rain can reach both seas. Water may split and follow several paths.
Examples
| heights | result |
|---|---|
[[1, 2, 2, 3, 5], [3, 2, 3, 4, 4], [2, 4, 5, 3, 1], [6, 7, 1, 4, 5], [5, 1, 1, 2, 4]] | 7 |
[[3, 3, 3], [3, 1, 3], [3, 3, 3]] | 8 |
[[7]] | 1 |
Example 1 — The cells are (0,4), (1,3), (1,4), (2,2), (3,0), (3,1), (4,0).
Example 2 — The centre is a pit; the 8 border cells reach both seas along the flat coast.
Example 3 — A single cell touches every coast.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(heights: int[][]) → int
Constraints
-
heights.length -
heights[i].length; all rows have the same length. -
heights[i][j]
Expected complexity
- Time
- O(HW)
- Space
- O(HW)
Examples
| heights | Expected |
|---|---|
[[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] | 7 |
[[3,3,3],[3,1,3],[3,3,3]] | 8 |
[[7]] | 1 |
Hint
Hint
Searching from every cell is . Search backwards instead: start a multi-source BFS from all top-row and left-column cells and step to a neighbour only if it is at least as high; the reached cells drain to the North-West Sea. Do the same from the bottom row and right column, and count cells marked by both searches. Use an explicit queue rather than recursion.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1108 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 5 | verdict only |