Problem 41 · Graphs
Number of Islands
01Problem
Given an m x n grid of '1' (land) and '0' (water), return the number of islands, where an island is a group of land cells connected horizontally or vertically.
02Key insight
Each unvisited land cell seeds a flood fill that marks its whole component; the number of seeds is the answer. Use an explicit stack (not recursion) so large grids don't blow the call stack.
03Solution
Try it first.
TimeO(m*n)
SpaceO(m*n)
tests.py · 4 passing
tests.pypython4 lines
assert num_islands([]) == 0
assert num_islands([["1","1","0"],["1","0","0"],["0","0","1"]]) == 2
assert num_islands([["0","0"],["0","0"]]) == 0
assert num_islands([["1","0","1","0","1"]]) == 304Staff-level follow-up
Grid too big for one machine? Shard into tiles, count islands per tile, then union-find the components touching shared tile borders to dedupe.