FastPrepNumber of Islands

Number of Islands

IMC Trading logoIMC Trading● MediumINTERNPHONE SCREEN
Learn

Problem statement

You are given a rectangular grid containing 0 for water and 1 for land.

An island is a maximal connected group of land cells. Connectivity uses only horizontal and vertical neighbors; diagonal contact does not connect islands.

Return the number of islands.

Function

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

Examples

Example 1

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

Count connected components of land using only horizontal and vertical adjacency.

Example 2

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

Count connected components of land using only horizontal and vertical adjacency.

Constraints

  • 1 <= grid.length <= 500
  • 1 <= grid[0].length <= 500
  • Every row has the same length and every cell is 0 or 1.

More IMC Trading problems

See IMC Trading hiring insights
public int numIslands(int[][] grid) {
    // Write your solution here.
}
grid[[1,1,0],[0,1,0],[0,0,1]]
expected2
Checking account…