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

Commit39e8398

Browse files
authored
200 Number of Islands Union Find solution (neetcode-gh#366)
1 parentf69bc1c commit39e8398

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

‎java/200-Number-of-Islands.java‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,80 @@ public void dfs(char[][] grid, int i, int j) {
2929
dfs(grid,i -1,j);
3030
dfs(grid,i,j -1);
3131
}
32+
33+
publicintnumIslandsUnionFind(char[][]grid) {
34+
intm =grid.length;
35+
intn =grid[0].length;
36+
UnionFinduf =newUnionFind(grid);
37+
int[][]dirs = {{1,0},{-1,0},{0,1},{0,-1}};
38+
39+
for (inti =0;i <m;i++)
40+
for (intj =0;j <n;j++)
41+
if (grid[i][j] =='1') {
42+
for (int[]dir :dirs) {
43+
intx =dir[0] +i;
44+
inty =dir[1] +j;
45+
46+
if (isSafe(grid,x,y)) {
47+
intid1 =i*n +j;
48+
intid2 =x*n +y;
49+
50+
uf.union(id1,id2);
51+
}
52+
}
53+
}
54+
55+
returnuf.count();
56+
}
57+
58+
privatebooleanisSafe(char[][]grid,intx,inty) {
59+
intm =grid.length;
60+
intn =grid[0].length;
61+
returnx >=0 &&x <m &&y >=0 &&y <n &&grid[x][y] !='0';
62+
}
63+
64+
classUnionFind {
65+
privateintcount;
66+
privateint[]parent,size;
67+
68+
publicUnionFind(char[][]grid) {
69+
intm =grid.length,n =grid[0].length;
70+
parent =newint[m*n];
71+
72+
for (inti =0;i <m;i++)
73+
for (intj =0;j <n;j++) {
74+
if (grid[i][j] =='1') {
75+
intid =i*n +j;
76+
parent[id] =id;
77+
count++;
78+
}
79+
}
80+
}
81+
82+
publicintfind(intp) {
83+
while(p !=parent[p]) {
84+
parent[p] =parent[parent[p]];
85+
p =parent[p];
86+
}
87+
88+
returnp;
89+
}
90+
91+
publicbooleanunion(intp,intq) {
92+
introot1 =find(p);
93+
introot2 =find(q);
94+
95+
if (root1 ==root2)
96+
returnfalse;
97+
98+
parent[root1] =root2;
99+
count--;
100+
101+
returntrue;
102+
}
103+
104+
publicintcount() {
105+
returncount;
106+
}
107+
}
32108
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp