-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumIslands200.java
More file actions
74 lines (64 loc) · 1.88 KB
/
Copy pathnumIslands200.java
File metadata and controls
74 lines (64 loc) · 1.88 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.LinkedList;
import java.util.Queue;
public class numIslands200 {
//深度优先算法
public int numIslands(char[][] grid) {
if(grid==null||grid.length==0) return 0;
int r=grid.length;
int l=grid[0].length;
int num_islands=0;
for(int i=0;i<r;i++){
for(int j=0;j<l;j++){
if(grid[i][j]=='1'){
num_islands++;
dfs(grid,i,j);
}
}
}
return num_islands;
}
public void dfs(char[][] grid,int r,int l){
int[] dx={1,0,0,-1};
int[] dy={0,1,-1,0};
int nr=grid.length;
int nl=grid[0].length;
if(r<0||l<0||r>=nr||l>=nl||grid[r][l]=='0'){
return;
}
grid[r][l] = '0';
for(int x=0;x<dx.length;x++){
int xr=r+dx[x];
int xy=l+dy[x];
dfs(grid,xr,xy);
}
}
//广度优先算法
//广度优先算法
public int numIslands2(char[][] grid){
int count=0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]=='1'){
bfs(grid, i, j);
count++;
}
}
}
return count;
}
private void bfs(char[][] grid,int i,int j){
Queue<int[]> list=new LinkedList<>();
list.add(new int[]{i,j});
while(!list.isEmpty()){
int[] cur=list.remove();
i= cur[0];j=cur[1];
if(0 <= i && i < grid.length && 0 <= j && j < grid[0].length && grid[i][j] == '1') {
grid[i][j] = '0';
list.add(new int[] { i + 1, j });
list.add(new int[] { i - 1, j });
list.add(new int[] { i, j + 1 });
list.add(new int[] { i, j - 1 });
}
}
}
}