200. 岛屿数量

题目描述

给你一个由 1(陆地)0(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

输入输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1

输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3

基本思路

深度优先搜索 经过的数组修改为2 时复$O(MN)$ 空复$O(MN)$

广度优先搜索 :

  1. 为了求出岛屿的数量,我们可以扫描整个二维网格。如果一个位置为 1,则将其加入队列,开始进行广度优先搜索。在广度优先搜索的过程中,每个搜索到的 1 都会被重新标记为 1。直到队列为空,搜索结束。

  2. 最终岛屿的数量就是我们进行广度优先搜索的次数。

  3. 时复$O(MN)$ 空复$O(min(M, N))$ 空复:最坏情况下均为陆地 队列大小的值

java实现

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
54
55
56
57
58
59
60
61
62
// 深搜 会修改二维数组中的值
class Solution {
public int result;
public int numIslands(char[][] grid) {
result = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == '1'){
dfs(grid, i, j);
result++;
}
}
}
return result;
}

private void dfs(char[][] grid, int row, int col){
if(row >= grid.length || col >= grid[0].length || row < 0 || col < 0){
return;
}
if(grid[row][col] != '1'){
return;
}
grid[row][col] = '2';
dfs(grid, row-1, col);
dfs(grid, row+1, col);
dfs(grid, row, col-1);
dfs(grid, row, col+1);

}
}

// 深搜 不会修改数组中的值 new一个visited[][]解决
class Solution {
public int numIslands(char[][] grid) {
int num_island = 0;
int[][] visited = new int[grid.length][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' && visited[i][j] != 1){
dfs(grid, i, j, visited);
num_island++;
}
}
}
return num_island;
}

private void dfs(char[][] grid, int row, int col, int[][] visited){
if(row >= grid.length || col >= grid[0].length || row < 0 || col < 0
|| grid[row][col] == '0' || visited[row][col] == 1){
return;
}

visited[row][col] = 1;
dfs(grid, row-1, col, visited);
dfs(grid, row+1, col, visited);
dfs(grid, row, col-1, visited);
dfs(grid, row, col+1, visited);

}
}