Skip to content

Number of Islands

MediumLeetCode #200Time O(m·n)Space O(m·n)

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.

11000
11000 -> 3
00100
00011

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 count
  • 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.
  • Bounds check first. Test r, c are inside the grid before reading grid[r][c].
  • Mutating the input. Sinking cells destroys the grid. If the interviewer says not to, use a visited set (O(m·n) extra space) or restore the cells afterwards.
  • Characters, not numbers. LeetCode gives "1" strings ('1' chars in Java). Comparing to 1 is a classic bug.
  • Diagonals don’t connect. Only 4 directions.

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.

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.

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.