Skip to content

Commit 967469c

Browse files
update 200 to more generic union find template
1 parent 0faa5d1 commit 967469c

File tree

1 file changed

+6
-28
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+6
-28
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_200.java

+6-28
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,5 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
* 200. Number of Islands
5-
* <p>
6-
* Given a 2d grid map of '1's (land) and '0's (water),
7-
* count the number of islands.
8-
* An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
9-
* You may assume all four edges of the grid are all surrounded by water.
10-
* <p>
11-
* Example 1:
12-
* 11110
13-
* 11010
14-
* 11000
15-
* 00000
16-
* Answer: 1
17-
* <p>
18-
* Example 2:
19-
* 11000
20-
* 11000
21-
* 00100
22-
* 00011
23-
* Answer: 3
24-
*/
253
public class _200 {
264

275
public static class Solution1 {
@@ -82,20 +60,20 @@ public UnionFind(char[][] grid) {
8260
}
8361

8462
public void union(int i, int j) {
85-
int x = find(ids, i);
86-
int y = find(ids, j);
63+
int x = find(i);
64+
int y = find(j);
8765
if (x != y) {
8866
/**note: this is when x != y, only in this case, we should union these two nodes, which makes sense naturally.*/
8967
count--;
9068
ids[x] = y;//ids[y] = x; //also works
9169
}
9270
}
9371

94-
public int find(int[] ids, int i) {
95-
if (ids[i] == i) {
96-
return i;
72+
public int find(int i) {
73+
if (i != ids[i]) {
74+
ids[i] = find((ids[i]));
9775
}
98-
return find(ids, ids[i]);
76+
return ids[i];
9977
}
10078
}
10179

0 commit comments

Comments
 (0)