1009. Split the Island
A map is stored in grid. A cell holding 0 is water and a cell holding any positive number is land; the number is only a height and does not matter. Land cells that touch horizontally or vertically form an island.
Each day you may sink exactly one land cell, turning it into water. The map is split when it no longer consists of exactly one island, which includes having two or more islands or none at all.
Return the minimum number of days needed to split the map. If the map already does not consist of exactly one island, return 0. It can be shown that the answer never exceeds 2.
Aim for O(R * C) time and space.
Example 1
- Input:
- grid = [[2,3,0,0],[0,1,4,0],[0,0,5,2]]
- Output:
- 1
- Explanation:
The answer is 1: removing one well-chosen land cell already splits the island.
Example 2
- Input:
- grid = [[3,3,1],[1,0,2],[2,2,1]]
- Output:
- 2
- Explanation:
The answer is 2: no single removal splits it but two removals do.
Constraints
1 ≤ R, C ≤ 250 where R x C is the size of grid
0 ≤ grid[i][j] ≤ 100
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(R*C)
- Space
- O(R*C)