-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_1971.java
More file actions
60 lines (52 loc) · 1.55 KB
/
Copy pathP_1971.java
File metadata and controls
60 lines (52 loc) · 1.55 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
package leetcode.easy;
public class P_1971 {
private static final class UnionFind {
private final int[] parent;
private final int[] size;
private int count;
private UnionFind(int n) {
parent = new int[n];
size = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int find(int p) {
// path compression
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p, int q) {
final int rootP = find(p);
final int rootQ = find(q);
if (rootP == rootQ) {
return;
}
// union by size
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
size[rootQ] = 0;
} else {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
size[rootP] = 0;
}
count--;
}
public int count() { return count; }
public int[] size() { return size; }
}
public boolean validPath(int n, int[][] edges, int start, int end) {
final UnionFind uf = new UnionFind(n);
for (int[] edge : edges) {
uf.union(edge[0], edge[1]);
}
return uf.find(start) == uf.find(end);
}
}