Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit24221e6

Browse files
number of islands using union find
1 parent120d72e commit24221e6

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
packagemedium;
2+
3+
/**
4+
* Created by fishercoder1534 on 9/30/16.
5+
*/
6+
7+
//Inspired by this post: https://discuss.leetcode.com/topic/39980/1d-union-find-java-solution-easily-generalized-to-other-problems
8+
publicclassNumberOfIslandsUnionFind {
9+
10+
classUnionFind{
11+
intcount;
12+
intm,n;
13+
int[]ids;
14+
15+
publicUnionFind(char[][]grid){
16+
m =grid.length;
17+
n =grid[0].length;
18+
ids =newint[m*n];
19+
for(inti =0;i <m;i++){
20+
for(intj =0;j <n;j++){
21+
if(grid[i][j] =='1') {
22+
count++;
23+
ids[i*n+j] =i*n+j;
24+
}
25+
}
26+
}
27+
}
28+
29+
publicvoidunion(inti,intj){
30+
intx =find(ids,i);
31+
inty =find(ids,j);
32+
if(x !=y) {//note: this is when x != y, only in this case, we should union these two nodes, which makes sense naturally.
33+
count--;
34+
ids[x] =y;
35+
}
36+
}
37+
38+
publicintfind(int[]ids,inti){
39+
if(ids[i] ==i)returni;
40+
returnfind(ids,ids[i]);
41+
}
42+
}
43+
44+
publicintnumIslands(char[][]grid) {
45+
if(grid ==null ||grid.length ==0 ||grid[0].length ==0)return0;
46+
int[]dirs =newint[]{0,1,0,-1,0};
47+
UnionFinduf =newUnionFind(grid);
48+
intm =grid.length,n =grid[0].length;
49+
for(inti =0;i <m;i++){
50+
for(intj =0;j <n;j++){
51+
if(grid[i][j] =='1'){
52+
for(intk =0;k <4;k++){
53+
intx =i+dirs[k];
54+
inty =j+dirs[k+1];
55+
if(x >=0 &&x <m &&y >=0 &&y <n &&grid[x][y] =='1'){
56+
intid1 =i*n+j;
57+
intid2 =x*n+y;
58+
uf.union(id1,id2);
59+
}
60+
}
61+
}
62+
}
63+
}
64+
returnuf.count;
65+
}
66+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp