All problems
1108MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix

Patches of Dry Ground Ringed by Water

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1254Number of Closed Islands

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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