Problems/200. Count Islands

200. Count Islands

MediumMatrixGraphDFSBFS

You are given a 2D grid representing a map of land cells (represented by 1s) and water cells (represented by 0s). Determine the total number of distinct islands.

An island is formed by connecting adjacent land cells horizontally or vertically. You may assume that all four edges of the grid are completely surrounded by water.

Example 1
Input: grid = [ [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1] ]
Output: 3
There are three distinct islands: one at the top-left (size 4), one near the center (size 1), and one at the bottom-right (size 2).
Example 2
Input: grid = [ [0, 0, 0], [0, 0, 0] ]
Output: 0
The grid contains only water, so there are zero islands.
Visualizer

Visualizer will appear here