Start learning free

LESSON 560 OF 671 · GRAPHS

Size of Islands

Practice O(n * m)

You get a grid where each cell is land (1) or water (0). Return an array with the size of every island in the grid.

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.

An island's size is how many land cells it has.

Example 1:

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

Output: [3, 5, 1]
Explanation: The green island at the top left has 3 cells.
The blue island along the right side has 5.
The red cell in the bottom left corner is an island of size 1.
Any order of the sizes is fine.

Example 2:

Input:
1 0 0
0 1 1

Output: [1, 2]
Explanation: The green cell meets the other land only at a corner.
It is an island of size 1.
The two blue cells in the bottom row form an island of size 2.

Example 3:

Input:
0 0
0 0

Output: []
Explanation: There is no land, so there are no islands.

 

Constraints:

  • 1 to 100 rows.
  • 1 to 100 columns.
  • Every cell is 0 or 1.

Note: The islands' sizes can be returned in any order

STEP 1 OF 16
    Ctrl + Enter to check