Problem · Array

Count Connected Islands

Learn this problem
MediumTwitch logoTwitchFULLTIMEONSITE INTERVIEW

Problem statement

You are given a rectangular binary grid encoded as an array of equal-length strings. Character 1 represents land and character 0 represents water.

An island is a maximal group of land cells connected through shared edges. Cells that touch only at a corner are not connected.

Return the number of islands. Do not modify the input grid.

Function

countIslands(grid: String[]) → int

Examples

Example 1

grid = ["110","010","101"]return = 3

The three connected components are the upper-left group, the land cell at the lower left, and the land cell at the lower right.

Example 2

grid = ["0000","0000"]return = 0

Every cell is water, so the grid contains no island.

Constraints

  • 1 <= grid.length <= 500
  • 1 <= grid[i].length <= 500
  • All rows have the same length.
  • Every character is 0 or 1.
  • grid.length * grid[i].length <= 2 * 10^5

More Twitch problems

drafts saved locally
public int countIslands(String[] grid) {
    // write your code here
}
grid["110","010","101"]
expected3
checking account