Start learning free

LESSON 4 OF 321 · FREE CODING INTERVIEW QUESTIONS

Number of Islands

Practice O(n * m)

You get a grid where each cell is land (1) or water (0). Return how many islands the grid has.

Land cells that share a side (up, down, left or right) belong to the same island. Cells that meet only at a corner don't. Everything around the grid is water.

Example 1:

Input:
0 1 1 0 0
0 1 0 0 1
1 1 0 1 1
1 0 0 0 1

Output: 2
Explanation: The green island and the blue island never share a side.

Example 2:

Input:
1 1 0 0 1
0 0 1 0 1
0 1 0 0 0

Output: 4
Explanation: The red cell and the orange cell touch other land only at corners.
So each of them is an island of its own.

Example 3:

Input:
0 0 0
0 0 0

Output: 0
Explanation: There is no land at all.

 

Constraints:

  • 1 to 100 rows.
  • 1 to 100 columns.
  • Every cell is 0 or 1.
STEP 1 OF 14
    Ctrl + Enter to check