Number of Closed Islands

Given a grid where 0 represents land and 1 represents water, return the number of closed islands. A closed island is a land component that is completely surrounded by water and does not touch the border. Pattern focus: Component traversal. Count only the components that never reach the boundary.

Input Format

grid = 2D binary matrix

Output Format

number of closed islands

Constraints

  • 1 <= rows * cols <= 10^5
  • Each cell is 0 or 1, where 0 is land.

Examples

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

Explanation:

There are two closed islands made of 0s.

Example 2:

Input:

grid = [[0,0,1,0,0],[0,1,1,1,0],[0,1,0,1,0],[0,1,1,1,0],[0,0,0,0,0]]

Output:

1

Explanation:

Only one land component of 0s is fully enclosed.

Example 3:

Input:

grid = [[1,1,1],[1,1,1],[1,1,1]]

Output:

0

Explanation:

There is no land at all.

Loading...
Number of Closed Islands - Graph Traversal