Number of Closed Islands

Medium Topics Company Tags

Here 0 represents land and 1 represents water. An island is a maximal group of land cells connected through shared edges, using up, down, left, or right moves. It is closed if none of its cells touches the outer boundary of the grid, so water surrounds it on every side. Count the closed islands. Diagonal contact does not connect two land cells.

Example 1:

Number of Closed Islands, example 1: illustration of the example

Input: grid = [[1,1,1],[1,0,1],[1,1,1]]

Output: 1

Explanation: The center land cell has water on all four sides and does not touch the grid boundary. It forms one closed island.

Example 2:

Number of Closed Islands, example 2: illustration of the example

Input: grid = [[1,0,1],[1,0,1],[1,1,1]]

Output: 0

Explanation: The center land cell connects to the land cell in the top row. That island reaches the boundary, so it is not closed.

Example 3:

Number of Closed Islands, example 3: illustration of the example

Input: grid = [[1,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,1]]

Output: 2

Explanation: The two interior land cells touch only diagonally. They are separate islands, each surrounded by water, giving 2 closed islands.

Constraints:

  • 1 <= grid.length <= 100
  • Every row has the same length, between 1 and 100.
  • Every entry is either 0 (land) or 1 (water).


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.