Skip to content
BASA DSA

Number of Islands

MediumGraphs

Count connected components of land in a rectangular grid. Cells containing string 1 are land and string 0 are water; connections are orthogonal.

Example 1

0,01I1
0,10
0,21I2
1,01I1
1,10
1,20
2,00
2,11I3
2,21I3
0 = water; 1 = land. Island labels I1 through I3 distinguish connected components; only horizontal and vertical neighbors connect.
Input
grid = [["1","0","1"],["1","0","0"],["0","1","1"]]
Output
3

Explanation

Three orthogonal components are (0,0)-(1,0), isolated (0,2), and (2,1)-(2,2). Diagonal contact does not join islands.

Example 2

0,00
0 = water; 1 = land. No land cells: zero islands; only horizontal and vertical neighbors connect.
Input
grid = [["0"]]
Output
0

Explanation

The single water cell contains no land, giving zero islands.

Example 3

0,01I1
0,11I1
1,01I1
1,11I1
0 = water; 1 = land. Island labels I1 through I1 distinguish connected components; only horizontal and vertical neighbors connect.
Input
grid = [["1","1"],["1","1"]]
Output
1

Explanation

All four land cells connect orthogonally into one island.

Constraints

  • 1 <= rows, columns <= 300

Function contractnumIslandsArguments: json
Loading draft…
SolutionRuns on your device
Loading draft…