FastPrepCount Connected Islands

Count Connected Islands

Uber logoUber● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given a rectangular binary matrix grid. A cell containing 1 is land and a cell containing 0 is water. Land cells belong to the same island when they are connected horizontally or vertically.

Return the number of islands.

Function

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

Examples

Example 1

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

All land cells are connected through horizontal or vertical moves.

Example 2

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

The top-left block, center cell, and bottom-right pair are separate islands.

Example 3

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

No cell is land.

Constraints

  • 1 <= grid.length <= 300.
  • 1 <= grid[i].length <= 300.
  • Every row has the same length.
  • Every value is 0 or 1.

More Uber problems

See Uber hiring insights
public int numberOfIslands(int[][] grid) {
    // Write your solution here.
}
grid[[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]
expected1
Checking account…