Number of Closed Islands

Given a 2D grid consisting of 0s representing land and 1s representing water, an island is a maximal 4-directionally connected group of 0s.

A closed island is an island totally surrounded by 1s on all four sides: left, top, right, and bottom.

Return the number of closed islands.

Example 1
1 1 1 1 1 1 1 0
1 0 0 0 0 1 1 0
1 0 1 0 1 1 1 0
1 0 0 0 0 1 0 1
1 1 1 1 1 1 1 0
Inputgrid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output2
Islands in gray are closed because they are completely surrounded by water, so there are 2 closed islands.
Example 2
0 0 1 0 0
0 1 0 1 0
0 1 1 1 0
Inputgrid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output1
There is exactly 1 island of land cells that is completely surrounded by water.

Constraints

  • 1 <= grid.length, grid[0].length <= 100
  • 0 <= grid[i][j] <=1

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate