Number of Islands
Count groups of connected land cells by sinking each island with DFS the first time you step on it.
The problem
You get a grid grid where "1" is land and "0" is water. An island is a group of land cells joined through up, down, left or right steps, with water or the edge of the grid all around it. Return the number of islands.
Input grid = [["1", "1", "0", "0"], ["0", "1", "0", "1"], ["1", "0", "0", "1"]]
Output 3
The three cells at the top left form one island, the two cells on the right form another, and the bottom-left cell is alone.
Input grid = [["1", "0", "1"], ["0", "1", "0"], ["1", "0", "1"]]
Output 5
Cells that touch only at a corner are not joined, so each of the five land cells is its own island.
Key constraint: The grid can be up to 300 by 300, so every cell should be handled a constant number of times: O(m * n) overall.
How to spot the pattern
- You must count connected groups in a grid.
- Every land cell belongs to exactly one group, and one search from any of its cells finds the whole group.
The idea
Scan the grid cell by cell. The first time you land on a "1", you have found a new island, so count it, then run a DFS from there that sinks every connected land cell by turning it into "0". Sinking means the rest of the scan never sees that island again, so each island is counted exactly once.
Brute force: For every land cell, run a fresh search to collect its whole island and compare it with the islands found so far, which repeats the same searches and costs O((m * n)^2) time.
Step by step
- 1Loop over every cell of the grid.
- 2When a cell is
"1", add one to the count and callsink(r, c). - 3In
sink, stop if the cell is outside the grid or is not"1". - 4Otherwise set the cell to
"0"and callsinkon its four neighbors. - 5Return the count after the scan.
See the pattern move
The graph bfs and dfs pattern on a small example. Step through it, or press play.
Code
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
rows, cols = len(grid), len(grid[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" # sink it so the scan never counts it again
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 # the first cell we see of a new island
sink(r, c)
return countComplexity
Time
O(m * n)
Space
O(m * n)
Every cell is visited a constant number of times; the recursion can go m * n calls deep when the whole grid is one winding island.
Watch out for
- Counting land cells instead of islands: count only when the scan finds land that no earlier search has sunk.
- Treating diagonal neighbors as joined.
- Comparing with the number 1 instead of the character
"1"; in Java and C++ the grid holds the char'1'.
Follow-up questions
What if you may not change the input grid?
Keep a separate visited grid and mark cells there instead of turning them into water. The time stays O(m * n), with O(m * n) extra space.
What if land is added one cell at a time and you must report the count after each addition?
Use union-find: each new land cell starts as its own island and is merged with its land neighbors, so each update takes nearly O(1). That is Number of Islands II.
In Hinglish
Grid scan karo; jaise hi koi "1" mile, count badhao aur DFS se poore island ko "0" bana do, taaki woh dobara count na ho.