200. Number of Islands

Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1
Example 2:

Input:
11000
11000
00100
00011

Output: 3

Solution

  1. BFS
    对于一个为1的位置,将其所有的邻居都加入队列,并置0(防止重复添加,降低效率)

  2. DFS
    对于一个为1的位置,递归将所有与其相邻的为1的位置置0

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
int res = 0;
Deque<Integer> q = new ArrayDeque<>();
int row = grid.length, col = grid[0].length;
for(int i = 0;i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == '1'){
res++;
q.offer(i*col + j);
while(!q.isEmpty()){
int num = q.poll();
int r = num / col, c = num % col;
grid[r][c] = '0';
if(r - 1 >= 0 && grid[r-1][c] == '1')
q.offer((r-1) * col + c);
if(r + 1 < row && grid[r+1][c] == '1')
q.offer((r+1) * col + c);
if(c+1 < col && grid[r][c+1] == '1')
q.offer(r*col + c+1);
if(c-1 >= 0 && grid[r][c-1] == '1')
q.offer(r*col + c - 1);
}
}
}
}
return res;
}

public int numIslands1(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
int res = 0;
for(int i = 0;i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == '1'){
res++;
zeroDfs(grid, i, j);
}
}
}
return res;
}

public void zeroDfs(char[][] grid, int i, int j){
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length
|| grid[i][j] == '0')
return;
grid[i][j] = '0';
zeroDfs(grid, i, j + 1);
zeroDfs(grid, i + 1, j);
zeroDfs(grid, i, j - 1);
zeroDfs(grid, i - 1, j);
}