Show problems as
Classic problem #1254MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix

Number of Closed Islands

Real-world version: Patches of Dry Ground Ringed by Water
Tracked in this browser only
Read Number of Closed Islands on LeetCode(opens in a new tab)

The 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.

Python
def closed_island(marsh: list[list[int]]) -> int:
Java
public int closedIsland(int[][] marsh)