InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Number of Islands

medium Original ↗ 00:00

Problem

You’re given an m x n grid of characters where '1' is land and '0' is water. An island is a maximal group of '1' cells connected horizontally or vertically (not diagonally). The grid is surrounded by water on all sides.

Return the number of islands.

Examples

  • grid = [["1","1","0"],["1","0","0"],["0","0","1"]]2 — the top-left L-shape of three 1s is one island; the lone 1 at the bottom-right is another.
  • grid = [["1","1","1"],["1","1","1"]]1 — every land cell is connected into a single island.
  • grid = [["0","0"],["0","0"]]0 — all water, no islands.

Constraints

  • 1 <= m, n <= 300
  • Each cell is '0' or '1'.
  • Connectivity is 4-directional (up/down/left/right), never diagonal.

Think about it first

Hint 1 An island is just a connected component of land cells. If you stand on one land cell and walk to every land cell you can reach, you've traced exactly one island.
Hint 2 Scan the grid. Each time you hit a `'1'` you haven't visited, that's a new island: run a DFS or BFS to flood-fill (mark) the whole island so it's counted only once. The number of flood-fills is the answer.
Hint 3 To mark visited cells without extra memory, overwrite each visited `'1'` with `'0'` (or `'#'`) as you go. Union-find is a valid alternative: union each land cell with its right and down land neighbors, then count roots among land cells.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug