Problems/1254. Closed Island

1254. Closed Island

MediumMatrixGraphDFSBFS

You are given a 2D binary grid where 0 represents land and 1 represents water. An island is a maximal 4-directionally connected group of land cells.

A closed island is an island that is completely (all four directions) surrounded by water cells (1s). This means it cannot touch any cell on the outer border of the grid. Return the number of closed islands.

Example 1
Input: grid = [ [1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 1, 1, 1, 1] ]
Output: 1
There is one closed island consisting of 0s in the center, which is completely isolated from the outer boundary by 1s.
Example 2
Input: grid = [ [1, 1, 1], [1, 0, 1], [1, 0, 1] ]
Output: 0
The island of 0s touches the bottom edge of the grid, so it is not a closed island.
Example 3
Input: grid = [ [1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1] ]
Output: 1
The island of two 0s in the center is completely surrounded by water and doesn't touch any boundary.
Visualizer

Visualizer will appear here