Number of Closed Islands

Given a 2D `grid` of `0`s (land) and `1`s (water), an island is a maximal group of land cells connected 4-directionally. A closed island is an island completely surrounded by water on its left, top, right and bottom, which means none of its cells lies on the edge of the grid. Return the number of closed islands.

30:00

Number of Closed Islands
medium
Free written solution
Topics
Companies

Given a 2D grid of 0s (land) and 1s (water), an island is a maximal group of land cells connected 4-directionally. A closed island is an island completely surrounded by water on its left, top, right and bottom, which means none of its cells lies on the edge of the grid. Return the number of closed islands.

Example 1:
Input: {"grid":[[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]]}
Output: 2
Constraints:
  • 1≤grid.length,grid[0].length≤1001 \leq \text{grid.length}, \text{grid}[0].\text{length} \leq 100

  • 0≤grid[i][j]≤10 \leq \text{grid}[i][j] \leq 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[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]]}

Scan the 5 x 8 grid row by row. Each unvisited land cell (0) starts a new island; it is closed only if no cell of it touches the edge.

islands

4

closed flag

-

count

0

water (1)

land (0)

flooding

closed island

touches edge

grid edge band

Variables
VariableValue
m5
n8
land15
count0
DepthFunction Call
Stack empty
0/24