Number of Islands
The problem
Section titled “The problem”You get a grid of "1" (land) and "0" (water). An island is a group of land cells
linked up, down, left or right (not diagonally). Return how many islands there are.
1100011000 -> 30010000011Key insight
Section titled “Key insight”Scan every cell. When you hit land you haven’t seen, that is a new island, so add 1. Then immediately flood fill from that cell: visit every land cell connected to it so you never count the same island twice.
The grid is an implicit graph: each cell’s neighbors are the 4 cells around it. To avoid a
separate visited set, overwrite visited land with "0" (“sink” it). The solution is DFS
with recursion. DFS can go as deep as the island is big, so a 300x300 all-land grid can
overflow the stack (Python’s default limit is about 1000). The fix is the same idea with
an explicit stack, or BFS with a queue. Mention this in the interview.
Show solutionHide solution
def num_islands(grid: list[list[str]]) -> int: rows = len(grid) cols = len(grid[0]) if rows else 0
def sink(r: int, c: int) -> None: if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1": return grid[r][c] = "0" # mark visited by sinking the land sink(r + 1, c) sink(r - 1, c) sink(r, c + 1) sink(r, c - 1)
count = 0 for r in range(rows): for c in range(cols): if grid[r][c] == "1": count += 1 # found a new island; erase all of it sink(r, c) return countexport function numIslands(grid: string[][]): number { const rows = grid.length; const cols = rows ? grid[0].length : 0;
function sink(r: number, c: number): void { if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] !== '1') return; grid[r][c] = '0'; // mark visited by sinking the land sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1); }
let count = 0; for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { if (grid[r][c] === '1') { count++; // found a new island; erase all of it sink(r, c); } } } return count;}class Solution { public int numIslands(char[][] grid) { int count = 0; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { if (grid[r][c] == '1') { count++; // found a new island; erase all of it sink(grid, r, c); } } } return count; }
private void sink(char[][] grid, int r, int c) { if (r < 0 || r >= grid.length || c < 0 || c >= grid[r].length || grid[r][c] != '1') return; grid[r][c] = '0'; // mark visited by sinking the land sink(grid, r + 1, c); sink(grid, r - 1, c); sink(grid, r, c + 1); sink(grid, r, c - 1); }}Complexity
Section titled “Complexity”- Time: O(m·n) — the scan touches each cell once, and each land cell is sunk (visited) once.
- Space: O(m·n) — worst case the recursion stack holds every cell (all land). No extra visited set.
Watch out for
Section titled “Watch out for”- Bounds check first. Test
r,care inside the grid before readinggrid[r][c]. - Mutating the input. Sinking cells destroys the grid. If the interviewer says not to,
use a
visitedset (O(m·n) extra space) or restore the cells afterwards. - Characters, not numbers. LeetCode gives
"1"strings ('1'chars in Java). Comparing to1is a classic bug. - Diagonals don’t connect. Only 4 directions.
Variations
Section titled “Variations”Max Area of Island (LeetCode 695)
Section titled “Max Area of Island (LeetCode 695)”Return the size of the largest island. The trick: make the flood fill return the number of cells it sank (1 plus the sum of the four recursive calls) and track the maximum.
Surrounded Regions (LeetCode 130)
Section titled “Surrounded Regions (LeetCode 130)”Flip every O region fully enclosed by X. The trick: work backwards. Flood fill
from the O cells on the border and mark them safe; everything unmarked is enclosed and
gets flipped.
Number of Provinces (LeetCode 547)
Section titled “Number of Provinces (LeetCode 547)”The input is an adjacency matrix of cities, not a grid. The trick: the same “count components” loop. For each unvisited city, DFS through everything it connects to and add 1.