Number of Closed Islands

MediumGraphsdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a 2D grid where 0 marks land and 1 marks water. An **island** is a maximal group of land cells connected horizontally or vertically (not diagonally). An island is **closed** if none of its cells lie on the outer border of the grid, which means it is completely surrounded by water on all four sides. Return the number of closed islands. Note the encoding: here 0 is land and 1 is water, the reverse of many other island problems.

Examples

Input: grid = [[1,1,1,1,1],[1,0,0,1,1],[1,0,1,0,1],[1,1,1,1,0]]
Output: 2
The island `{(1,1),(1,2),(2,1)}` and the single cell `(2,3)` are both enclosed by water. The land at `(3,4)` touches the border, so it does not count.
Input: grid = [[0,0,1],[1,0,1],[1,1,1]]
Output: 0
The only island includes cells on the top edge, so there are no closed islands.

Constraints

  • 1 <= grid.length, grid[0].length <= 100
  • `grid[i][j]` is `0` or `1`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems