Problem Description
Given a 2D grid consisting of 0s (land) and 1s (water), an island is defined as a maximal group of 0s connected 4-directionally. A "closed island" is an island that is completely surrounded by water (i.e., all its boundaries—left, top, right, bottom—are water). The task is to count the number of closed islands in the grid.
Key Insights
- Flood-fill (using DFS/BFS) can be used to traverse and "sink" islands.
- First, eliminate islands connected to the grid border because they cannot be closed.
- Then, iterate over the inner grid cells and count islands that are completely surrounded by water.
- Time complexity is O(m*n) where m and n are the grid dimensions.
- Space complexity depends on recursion depth or queue used in traversal, which in worst-case is O(m*n).
Space and Time Complexity
Time Complexity: O(mn)
Space Complexity: O(mn) (in worst-case, for the recursion stack or BFS queue)
Solution
Use Depth-First Search (DFS) to traverse the grid. The algorithm has two main phases. In the first phase, iterate over the border cells and perform DFS on any cell that is a land (0) to mark all reachable land cells as water (1). This ensures that we do not count islands that are connected to the border. In the second phase, iterate over the entire grid (ignoring the borders) and perform DFS on any remaining land cell. Each DFS call here represents one closed island and increments the count. Mark all visited cells during DFS to avoid recounting.