Problem
Given a 2D grid of '1' (land) and '0' (water), return the number of islands. An island is a group of land cells connected four-directionally.
Original: LeetCode 200: Number of Islands.
Examples
Example 1
`grid = [["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"]]``1`Example 2
`grid = [["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"]]``3`Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is'0'or'1'.
Hints
Hint 1
Diagonal connections do not count. The grid can contain several islands, or none.
Hint 2
Connected components on a grid are a DFS or BFS flood fill, or a union-find over land cells.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. You still have to visit every cell; the work is in not recounting the same island.
Optimal. When you see a '1', increment the answer and recursively set all connected '1's to '0' (or to a visited flag).
Alternative. Union-find: union a land cell with its right and down neighbours, then count the number of roots among land cells.
Complexity
- Time
- O(rows * cols)
O(rows * cols) time, because each cell is visited a constant number of times. The recursion depth can be O(rows * cols) in a worst-case spiral of land; a BFS queue has the same bound in memory.
- Space
- O(rows * cols)
Code
def num_islands(grid: list[list[str]]) -> int:
rows, cols = len(grid), len(grid[0])
def dfs(r: int, c: int) -> None:
if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != "1":
return
grid[r][c] = "0"
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
count += 1
dfs(r, c)
return count
if __name__ == "__main__":
a = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"],
]
assert num_islands(a) == 1
b = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"],
]
assert num_islands(b) == 3
print("ok")public class NumberOfIslands {
static int numIslands(char[][] grid) {
int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1') {
count++;
dfs(grid, r, c);
}
}
}
return count;
}
static void dfs(char[][] grid, int r, int c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] != '1') return;
grid[r][c] = '0';
dfs(grid, r + 1, c);
dfs(grid, r - 1, c);
dfs(grid, r, c + 1);
dfs(grid, r, c - 1);
}
public static void main(String[] args) {
char[][] a = {
{'1','1','1','1','0'},
{'1','1','0','1','0'},
{'1','1','0','0','0'},
{'0','0','0','0','0'}
};
if (numIslands(a) != 1) throw new AssertionError();
char[][] b = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};
if (numIslands(b) != 3) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: the first grid is one island, and the second grid is three islands.
- Mutating the input is allowed in the usual interview version; if not, keep a visited matrix.
Follow-ups
- Max Area of Island returns the size of the largest component instead of the count.
- Number of Provinces is the same idea on an adjacency matrix rather than a grid.
Interview script
"Each unvisited land cell starts a new island. I flood-fill that component so I never count its cells again. The whole scan is linear in the size of the grid."
Source: LeetCode 200: Number of Islands
Sources (1)
- LeetCode 200: Number of Islandsleetcode.com