FastPrepCount the Islands

Count the Islands

Adobe logoAdobe● MediumFULLTIMEPHONE SCREEN

Updated

Problem statement

You are given a grid of m rows and n columns. A cell with 1 is land and a cell with 0 is water. Two land cells belong to the same island when you can walk from one to the other through land cells, each step going up, down, left or right (not diagonally). Everything outside the grid is water.

Return the number of islands.

Function

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

Examples

Example 1

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

The cells (0,0), (0,1) and (1,1) touch side by side and form one island. (1,3) and (2,3) form a second. (2,0) touches (1,1) only at a corner, which does not count, so it is a third island. The answer is 3.

Example 2

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

There is no land, so there are no islands.

Example 3

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

Three single cells of land separated by water: 3 islands.

Constraints

  • 1 <= m, n <= 100, where m is the number of rows and n the number of columns
  • every row of grid has n cells
  • grid[r][c] is 0 or 1

More Adobe Phone Screen questions

Similar questions at other companies

Interview reports that mention this question

Adobe interview experiences

All Adobe interview questionsSee Adobe hiring insights
Saved
class Solution {
    public int countIslands(int[][] grid) {
        // Write your code here.
    }
}
Checking account…