DIY: Number of Islands

Solve the interview question "Number of Islands" yourself in this lesson.

We'll cover the following

Problem statement

Given an m x n 2D grid map of 1's (land) and 0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water.

Input

The input will be in the form of a 2D matrix. The following is an example input:

grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]

Output

The output will be an integer representing the number of islands. The following is an example output:

3

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.