-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindIfPathExistsInGraph.java
46 lines (40 loc) · 1.01 KB
/
FindIfPathExistsInGraph.java
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
/* https://leetcode.com/problems/find-if-path-exists-in-graph/?envType=daily-question&envId=2024-04-21 */
/* 1971. Find if Path Exists in Graph */
class UnionFind {
public UnionFind(int n) {
id = new int[n];
rank = new int[n];
for (int i = 0; i < n; ++i)
id[i] = i;
}
public void unionByRank(int u, int v) {
final int i = find(u);
final int j = find(v);
if (i == j)
return;
if (rank[i] < rank[j]) {
id[i] = j;
} else if (rank[i] > rank[j]) {
id[j] = i;
} else {
id[i] = j;
++rank[j];
}
}
public int find(int u) {
return id[u] == u ? u : (id[u] = find(id[u]));
}
private int[] id;
private int[] rank;
}
class FindIfPathExistsInGraph {
public boolean validPath(int n, int[][] edges, int source, int destination) {
UnionFind uf = new UnionFind(n);
for (int[] edge : edges) {
final int u = edge[0];
final int v = edge[1];
uf.unionByRank(u, v);
}
return uf.find(source) == uf.find(destination);
}
}