Skip to content

Commit ed33ddd

Browse files
authored
Create Find if Path Exists in Graph.java
1 parent e170bbf commit ed33ddd

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//1971. Find if Path Exists in Graph
2+
class DisjointSetUnion{
3+
private int[] parent;
4+
private int[] rank;
5+
private int N;
6+
7+
public DisjointSetUnion(int n){
8+
this.N = n;
9+
this.parent = new int[this.N];
10+
this.rank = new int[this.N];
11+
for(int i = 0; i < this.N; i++){
12+
this.parent[i] = i;
13+
this.rank[i] = 1;
14+
}
15+
}
16+
17+
public boolean areConnected(int u, int v){
18+
return find(u) == find(v);
19+
}
20+
21+
public void union(int u, int v){
22+
if(u != v){
23+
int a = find(u);
24+
int b = find(v);
25+
if(a != b){
26+
if(rank[a] > rank[b]){
27+
parent[b] = a;
28+
rank[a] += rank[b];
29+
}else{
30+
parent[a] = b;
31+
rank[b] += rank[a];
32+
}
33+
}
34+
}
35+
}
36+
37+
private int find(int u){
38+
int x = u;
39+
while(x != this.parent[x]){
40+
x = this.parent[x];
41+
}
42+
43+
this.parent[u] = x;
44+
return x;
45+
}
46+
}
47+
48+
class Solution {
49+
public boolean validPath(int n, int[][] edges, int start, int end) {
50+
DisjointSetUnion set = new DisjointSetUnion(n);
51+
for(int[] edge : edges){
52+
set.union(edge[0], edge[1]);
53+
}
54+
55+
return set.areConnected(start, end);
56+
}
57+
}

0 commit comments

Comments
 (0)