AceYourInterviews
Checking sign-in…

93. Number of Islands

IntermediateConnected components in a grid

Count groups of land cells connected through up, down, left, or right moves. Each such connected group is one island.

Diagonal contact alone does not connect islands. All cells in one connected group count together, regardless of the group's shape.

Example 1

Input

["110","010","001"]

Output

2

Explanation: The top-left component contains three cells; the bottom-right land cell is diagonally separated.

Example 2

Input

["10","01"]

Output

2

Explanation: The two land cells share no orthogonal edge.

Constraints

  • 0 <= rows, columns <= 100
  • Each cell is '0' or '1'. The grid is rectangular.
Hints
Hint 1

View every land cell as a vertex.

Hint 2

One traversal exhausts exactly one component.

Hint 3

Scan all cells, start only on unvisited land, and mark neighbors on discovery.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Separate diagonal component

[[1,1,0],[0,1,0],[0,0,1]]
2