Count islands - aloalgo

Count islands

Medium

You are given a 2D grid of 1's (land) and 0's (water).

Your task is to count the number of islands.

You may assume that:

  • An island is defined as a group of land cells (1's) connected vertically and horizontally.
  • Land connected diagonally does not count as part of the same island.

Return an integer representing the total number of islands.

Example 1

Input
[
  [1, 1, 1, 1],
  [1, 0, 0, 1],
  [1, 0, 0, 1],
  [1, 1, 1, 1]
]
Output
1
Explanation:

All land cells are connected, forming a single island.

Example 2

Input
[
  [0, 1, 1],
  [1, 0, 0],
  [1, 0, 1]
]
Output
3
Explanation:

There are three islands: {(0,1),(0,2)}, {(1,0),(2,0)}, and {(2,2)}.

Loading...
Input
[
  [1, 1, 1, 1],
  [1, 0, 0, 1],
  [1, 0, 0, 1],
  [1, 1, 1, 1]
]
Output
1

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!