Problem · Array

Count Islands in a Binary Grid

Learn this problem
MediumApple logoAppleFULLTIMEPHONE SCREEN

Problem statement

Given a rectangular binary grid, return the number of islands.

Each cell is either 1 for land or 0 for water. An island is a maximal group of land cells connected vertically or horizontally. Diagonal cells are not connected.

Function

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

Examples

Example 1

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

The land in the upper-left forms one island. The three connected land cells on the right form a second island.

Example 2

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

The grid contains no land, so it contains no islands.

Example 3

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

Every land cell touches the others only diagonally. Because diagonal contact does not connect islands, all five land cells are separate.

Constraints

  • 1 <= grid.length <= 300.
  • 1 <= grid[r].length <= 300 for every row r.
  • All rows have the same length.
  • Every cell is either 0 or 1.
  • The caller does not require the input grid to remain unchanged.

More Apple problems

drafts saved locally
public int countIslands(int[][] grid) {
    // Write your code here.
}
grid[[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,0]]
expected2
checking account