FastPrepCount Four-Neighbor Islands

Count Four-Neighbor Islands

NVIDIA logoNVIDIA● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Given a rectangular grid of 0 (water) and 1 (land), count its islands.

For this practice, land cells belong to the same island when connected through their top, bottom, left, or right sides. Diagonally touching cells are separate unless a path of side-connected land joins them. Each land cell belongs to exactly one island. Return 0 for an empty grid.

Function

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

Examples

Example 1

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

The three connected upper-left land cells form one island, and the lower-right cell forms another.

Example 2

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

The two land cells meet only diagonally, so they form two islands.

Example 3

grid = []return = 0

There are no land cells in an empty grid.

Constraints

  • 0 <= grid.length <= 50.
  • When the grid is nonempty, every row has the same length between 1 and 50.
  • Every cell is 0 or 1.
  • The input grid need not be modified.

More NVIDIA problems

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