ExamAdda Logo

Number of Islands

Easy

Given an m × n 2D grid containing:

'1' → Land

'0' → Water

 

find the number of islands.

An island is formed by connecting adjacent land cells horizontally or vertically.

Diagonal cells are not considered connected.

Example

1 1 0 0 0

1 1 0 0 0

0 0 1 0 0

0 0 0 1 1

 

There are 3 islands:

Island 1:

1 1

1 1

Island 2:

1

Island 3:

1 1

 

So the answer is:

3

Main Idea

Traverse every cell.

Whenever we find an unvisited land cell:

grid[i][j] == '1'

 

we have discovered a new island.

Then perform DFS or BFS to visit all connected land cells belonging to that island.

Increase the island count by 1.

Example 1

Input

4 5
1 1 1 1 0
1 1 0 1 0
1 1 0 0 0
0 0 0 0 0

Output

1

Explanation

All the land cells are connected horizontally or vertically.

1 1 1 1 0

1 1 0 1 0

1 1 0 0 0

0 0 0 0 0

 

Although there are several separated-looking groups, every 1 belongs to the same connected component.

Therefore:

Number of islands = 1

Example 2

Input

4 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1

Output

3

Explanation

There are three separate groups of land:

Island 1:

1 1

1 1

 

Island 2:

1

 

Island 3:

1 1

 

The second and third islands are not connected diagonally.

Therefore:

3 islands

Constraints

1 <= m
n <= 300
grid[i][j] is '0' or '1'

Hints:

Hint 1

Every time you encounter a 1 that has not been visited, you have found a new island.

Hint 2

Use DFS or BFS to visit all horizontally and vertically connected land cells.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 15, 2026

Last updated

Aug 15, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output