#200 Number of Islands

MediumGraphs~20 min

You're given a 2D grid of characters where '1' marks land and '0' marks water. An island is a maximal group of land cells connected horizontally or vertically (diagonal contact doesn't count). Everything beyond the grid's edges is water.

Return how many islands the grid contains.

Examples

Inputgrid = [["1","1","0","0"],["1","1","0","0"],["0","0","1","0"],["0","0","0","1"]]
Output3

The 2×2 block top-left is one island; the two lone 1s bottom-right are two more. They touch only diagonally, which doesn't connect them.

Inputgrid = [["1","0","1"],["0","1","0"],["1","0","1"]]
Output5

A checkerboard: no two land cells share an edge, so every 1 is its own island.

Constraints

  • 1 ≤ rows, cols ≤ 300
  • grid[i][j] is '1' or '0'

The explainer is the good part.

Sign in for the full intuition build-up, every approach from naive to optimal with complexity analysis, progressive hints, and commented solutions in Python, JavaScript, and Java. All free.

Want a taste first? Try a free sample: Two Sum or Valid Parentheses.