Problem · Matrix

Number of Islands

Learn this problem
MediumCrowdStrike logoCrowdStrikeFULLTIMEONSITE INTERVIEW

Problem statement

Given an array of equal-length strings grid, where '1' represents land and '0' represents water, return the number of islands.

An island is a maximal group of land cells connected horizontally or vertically. Cells outside the matrix are water.

Function

countIslands(grid: String[]) → int

Examples

Example 1

grid = ["11110","11010","11000","00000"]return = 1

All land cells belong to one orthogonally connected component.

Example 2

grid = ["11000","11000","00100","00011"]return = 3

The upper-left block, center cell, and lower-right pair are separate islands.

Constraints

  • 1 <= grid.length <= 300.
  • 1 <= grid[i].length <= 300 and every row has the same length.
  • Every character is '0' or '1'.
drafts saved locally
public int countIslands(String[] grid) {
    // Write your code here.
}
grid["11110","11010","11000","00000"]
expected1
checking account