FastPrepNumber of Closed Islands

Number of Closed Islands

Snap Inc. logoSnap Inc.● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

A rectangular grid contains land cells marked 0 and water cells marked 1. Land cells belong to the same island when connected horizontally or vertically.

Return the number of islands made entirely of land cells that do not touch the grid boundary.

Function

closedIsland(grid: int[][]) → int

Examples

Example 1

grid = [[1,1,1,1,1],[1,0,0,1,1],[1,0,1,0,1],[1,1,1,1,1]]return = 2

The left group of three land cells and the isolated land cell are both closed.

Example 2

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

The only island reaches the boundary.

Example 3

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

The center land cell is fully enclosed.

Constraints

  • 1 <= grid.length, grid[i].length <= 100.
  • The grid is rectangular and contains only 0 and 1.

More Snap Inc. problems

See Snap Inc. hiring insights
public int closedIsland(int[][] grid) {
    // Write your code here.
}
grid[[1,1,1,1,1],[1,0,0,1,1],[1,0,1,0,1],[1,1,1,1,1]]
expected2
Checking account…