Number of Islands

Given a 2D grid of '0' and '1' cells, return the number of islands. An island is formed by horizontally or vertically adjacent land cells. Pattern focus: DFS. Traverse each unseen land cell, mark its entire connected component, and count how many components exist.

Input Format

grid = 2D binary matrix

Output Format

number of islands

Constraints

  • 1 <= rows * cols <= 10^5
  • Each grid cell is either 0 or 1.

Examples

Example 1:

Input:

grid = [["1","1","0"],["0","1","0"],["1","0","1"]]

Output:

3

Explanation:

There are three connected groups of 1s using four-directional adjacency.

Example 2:

Input:

grid = [["0","0"],["0","0"]]

Output:

0

Explanation:

No land cells are present.

Example 3:

Input:

grid = [["1","1"],["1","1"]]

Output:

1

Explanation:

All land cells belong to one island.

Loading...
Number of Islands - Graph Traversal DSA Problem