DIY: Number of Islands

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

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

Coding exercise

Implement the num_islands(islands) function, where islands is the 2D matrix of 1's and 0's. The function returns an integer representing the number of islands calculated from the matrix.

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