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
|
public static int numIslands(char[][] board){
int n = board.length;
int m = board[0].length;
build(n,m,board);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j]=='1'){
if(j>0&&board[i][j-1]=='1'){
union(i,j,i,j-1);
}
if(i>0&&board[i-1][j]=='1'){
union(i,j,i-1,j);
}
}
}
}
return sets;
}
public static int MAXSIZE = 100001;
public static int[] father = new int[MAXSIZE];
public static int cols;
public static int sets;
public static void build(int n,int m,char[][] board){
cols = m;
sets = 0;
for(int a=0;a<n;a++){
for(int b=0,index;b<m;b++){
if(board[a][b]=='1'){
index = index(a,b);
father[index]=index;
sets++;
}
}
}
}
public static int index(int a,int b){
return a*cols+b;
}
public static int find(int i){
if(i!=father[i]){
father[i]=find(father[i]);
}
return father[i];
}
public static void union(int a,int b,int c,int d){
int fx = find(index(a, b));
int fy = find(index(c, d));
if(fx!=fy){
father[fx]=fy;
sets--;
}
}
|