Number of islands
We'll cover the following
In a grid of land (1) and water (0), count the islands. Land touching up, down, left or right is the same island.
Watch it run
Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.
0011001
0011100
1010001
0111011
0000010
1000101
1011110
Scan the grid. 1 is land and 0 is water. Each time we meet unvisited land we have found a new island.
islands 0
1 / 36
The idea
Complexity
| Time | Space | Why |
|---|---|---|
O(R × C) | O(R × C) | Each cell is filled once; the recursion can be as deep as one big island. |
In Python
def num_islands(grid):
R, C, count = len(grid), len(grid[0]), 0
def fill(r, c):
if not (0 <= r < R and 0 <= c < C) or grid[r][c] != '1': return
grid[r][c] = '0' # mark visited
fill(r+1, c); fill(r-1, c); fill(r, c+1); fill(r, c-1)
for r in range(R):
for c in range(C):
if grid[r][c] == '1':
count += 1; fill(r, c)
return countSummary: say it in the interview
- Scan the grid. When you meet land you have not seen, count one island and flood-fill every connected land cell so it is never counted again. BFS or DFS both work.
- Time O(R × C), space O(R × C). Each cell is filled once; the recursion can be as deep as one big island.