Graphs Grids as graphs
441. Number of Closed Islands
You are given a map as a grid of integers, grid, with m rows and n columns. In this problem, a
cell that holds 0 is land, and a cell that holds 1 is water. That is the opposite of Number of Islands.
An island is a group of land cells joined by steps up, down, left or right. Two land cells that touch only at a corner are not joined. An island is closed when none of its cells is on the edge of the grid, so water surrounds it on every side.
Return the number of closed islands in grid.
Example 1
Input: grid = [[1, 1, 1, 1, 1, 1, 0],
[1, 0, 0, 1, 1, 1, 0],
[1, 0, 1, 1, 0, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[0, 0, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 1, 1]]
2Explanation: The 0s form four islands. The three cells at the top left and the five cells in the middle are closed. The pair in the top right corner and the three cells at the bottom left are on the edge, so they are not.
Example 2
Input: grid = [[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 0, 1]]
0Explanation: The ring of land reaches the bottom row at row 4, column 3, so it is not closed. The water in the middle of the ring does not change that.
Example 3
Input: grid = [[0, 1, 0, 0, 1]]
0Explanation: With only one row, every cell is on the edge, so no island can be closed.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
m == grid.length,n == grid[i].length1 ≤ m, n ≤ 300grid[i][j]is 0 (land) or 1 (water).
Clarifying questions
What you would ask an interviewer before writing any code.