InterviewPrepKit

Home / Coding / Graphs

Number of Islands

medium Original ↗
Solving tips
  • This is connected-components counting on a grid: scan for an unvisited '1', flood-fill (DFS/BFS) its whole component sinking cells to '0', and increment the count; O(m*n).
  • Overwrite visited land to '0' (or '#') for O(1) extra space, or use a separate visited set if the caller needs the grid intact.
  • In BFS mark a cell visited on enqueue, not dequeue, so it can't enter the queue multiple times.
  • Pitfall: connectivity is 4-directional only; on a near-full 300x300 grid recursive DFS can overflow the stack, so prefer BFS or union-find there.

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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.