Number of Islands

Medium

Question

You're given a 2D grid representing a map that consists of '1's (land) and '0's (water). An island is a group of adjacent land that's surrounded by water vertically or horizontally.

Return the number of islands on the map.

Number of Islands Example 1

Input: grid = [[1, 0 ], [0, 1]]

Output: 2

There are two separate islands in the corner of the grid.

Number of Islands Example 2

Input: grid = [[1, 1, 1, 1, 0], [0, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]]

Output: 1

There is a single island in the top left corner of the grid.

Number of Islands Example 3

Input: grid = [[1, 1, 1, 1, 1], [1, 0, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 0, 1], [1, 0, 1, 1, 1]]

Output: 3

There are three islands in this grid, one in the top-left edges, a second in the center, and a third in the bottom right corner of the grid.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

How many islands are in this map? grid = [[1, 0, 1], [0, 1, 1], [1, 0, 1]]
1
2
3
4

Login or signup to save your code.

Notes