200. Number of Islands

200. Number of Islands

Question

Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return 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.

Solution

遍历所有点,如果等于1则对其进行DFS搜索。
在搜索的同时将1设为0。
如果等于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
class Solution {
char[][] area;
public int numIslands(char[][] grid) {
area = grid;
int count = 0;

for(int i = 0; i < area.length; i++){
for(int j = 0; j < area[0].length; j++){
if(area[i][j] == '1'){
dfs(i, j);
count++;
}
}
}
return count;
}

private void dfs(int i, int j){
if(area[i][j] == '0'){
return;
}
area[i][j] = '0';

if( i+1 < area.length ){
dfs(i+1, j);
}
if( i-1 >= 0 ){
dfs(i-1, j);
}
if( j+1 < area[0].length ){
dfs(i, j+1);
}
if( j-1 >= 0 ){
dfs(i, j-1);
}
}
}

Solution 2

同样是dfs搜索遍历每个位置,然而这个方法使用visited[][]数组来记录点是否被访问过。

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
class Solution {
int[][] visited;
char[][] map;
int[][] operations;
public int numIslands(char[][] grid) {
visited = new int[grid.length][grid[0].length];
map = grid;
int count = 0;
operations = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(visited[i][j] == 1 || map[i][j] == '0') continue;
dfs(i, j);
count++;
}
}
return count;
}

private void dfs(int x, int y){
if(x < 0 || x >= map.length || y < 0 || y >= map[0].length ) return;
if(visited[x][y] == 1 || map[x][y] == '0') return;
visited[x][y] = 1;
for(int[] operation : operations){
int m = x + operation[0];
int n = y + operation[1];
dfs(m, n);
}

}
}
Author

Xander

Posted on

2022-04-20

Updated on

2022-08-28

Licensed under

Comments