forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfIslands_200.java
More file actions
94 lines (75 loc) · 2.21 KB
/
NumberOfIslands_200.java
File metadata and controls
94 lines (75 loc) · 2.21 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package LeetCode;
import java.util.HashMap;
import java.util.Map;
/**
* @Classname NumberOfIslands_200
* @Description 给定一个二维数组,求岛屿的数目
* 思路:首先是建立一个图,目标:寻找连通图的个数!!!
* 方法二:将所有连通的点都变为0,dfs!!!!!!!!!!
* @Date 19-5-20 下午5:20
* @Created by mao<[email protected]>
*/
public class NumberOfIslands_200 {
public int numIslands(char[][] grid) {
//建立HashMap
// <a,b> 节点a指向节点b
Map<Integer,Integer> map=new HashMap<>();
//行数
int m=grid.length;
//列数
int n=grid[0].length;
for(int i=0;i<m;i++){
for (int j=0;j<n;j++){
//在中间范围内
if(0<i&&i<m&&0<j&&j<n){
if(grid[i][j]=='1'){
if(grid[i-1][j]=='1'){
map.put(i*n+j,(i-1)*n+j);
}
if(grid[i+1][j]=='1'){
map.put(i*n+j,(i+1)*n+j);
}
if(grid[i][j-1]=='1'){
map.put(i*n+j,i*n+j-1);
}
if(grid[i][j+1]=='1'){
map.put(i*n+j,i*n+j+1);
}
}
}
//边缘部分
}
}
return helper(map);
}
//从连通图中获取
public int helper(Map<Integer,Integer> map){
return 0;
}
public int numIslands_2(char[][] grid) {
//行数
int m=grid.length;
//列数
int n=grid[0].length;
int ans=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]=='1'){
ans+=1;
dfs(grid,i,j,m,n);
}
}
}
return ans;
}
public void dfs(char[][] grid,int x,int y,int m,int n){
if(x<0 || y<0 || x>=m || y>=n || grid[x][y]=='0'){
return;
}
grid[x][y]='0';
dfs(grid,x+1,y,m,n);
dfs(grid,x-1,y,m,n);
dfs(grid,x,y-1,m,n);
dfs(grid,x,y+1,m,n);
}
}