Number of Closed Islands
Real-world version: Patches of Dry Ground Ringed by WaterThe statement here is our own: the same inputs, outputs and technique.
A map marsh holds only 0 and 1, where 0 marks dry ground and 1 marks water. Two dry cells belong to the same patch when they share a side, so up, down, left or right; touching only at a corner does not join them.
A patch is enclosed when none of its cells lies on the outer edge of the map, which means water rings it on every side.
Return how many patches are enclosed.
Examples
Example 1
- Input
- marsh = [[1, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 1]]
- Output
- 2
The two dry cells meet only at a corner, which does not join them, so each is a patch of its own. Neither lies on the outer edge, so both are enclosed.
Example 2
- Input
- marsh = [[1, 1, 1], [1, 0, 0], [1, 1, 0]]
- Output
- 0
The three dry cells form one patch and two of them sit in the map's last column, so the patch is open.
Example 3
- Input
- marsh = [[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]]
- Output
- 1
The eight dry cells form a single ring around a water cell in the middle. None of them touches the outer edge, so the ring counts once.
Constraints
- 1 <= marsh.length <= 100
- 1 <= marsh[i].length <= 100
- 0 <= marsh[i][j] <= 1
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def closed_island(marsh: list[list[int]]) -> int:public int closedIsland(int[][] marsh)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's