oneby7

Graphs Grids as graphs

441. Number of Closed Islands

Medium

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

111111010011101011011111000100110111011111

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]]

Output: 2

Explanation: 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

1111110001101011000111101

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]]

Output: 0

Explanation: 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

01001

Input: grid = [[0, 1, 0, 0, 1]]

Output: 0

Explanation: 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.

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

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 300
  • grid[i][j] is 0 (land) or 1 (water).

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.