1. Description
In the binary matrix grid, 0 represents land and 1 represents water.
An island consists of a maximal group of land cells connected horizontally or vertically. It is closed when water surrounds it on all four sides, with no land cell in the group touching the grid boundary.
Count how many islands are closed.
2. Example
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: The large land component in the interior and the single land cell at row 3, column 6 are surrounded by water. All other land components touch the boundary. Coordinates are zero-based.
Example 2
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1
Explanation: Only the land cell at row 1, column 2 forms a closed island. The other land components reach the boundary.
Example 3
Input: grid = [[1,1,1,1,1,1,1],[1,0,0,0,0,0,1],[1,0,1,1,1,0,1],[1,0,1,0,1,0,1],[1,0,1,1,1,0,1],[1,0,0,0,0,0,1],[1,1,1,1,1,1,1]]
Output: 2
Explanation: The ring of land and the isolated central land cell form two separate closed islands.
3. Constraints
- 1 <= grid.length, grid[0].length <= 100
- 0 <= grid[i][j] <= 1
4. Solutions
Breadth-First Search
m = grid.size(), n = grid.front().size()
Time complexity: O(mn)
Space complexity: O(mn)
| |