Leetcode in Java && Oracle
424 subscribers
8 photos
397 files
400 links
Second channel: @codeforces_java

Let's Develop Together!
Download Telegram
image_2023-01-16_01-04-58.png
49.8 KB
Runtime9 msBeats96.66%
Memory117.2 MBBeats89.51%

#N1971. Find if Path Exists in Graph
problem link
#solution
class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
int[] parents=new int[n];
for(int i=0; i<n; i++) parents[i]=i;

for(int[] edge: edges){
int p1=find(parents, edge[0]);
int p2=find(parents, edge[1]);

if(p1<p2) parents[p2]=p1;
else parents[p1]=p2;
}

return find(parents, source) == find(parents, destination);
}
public int find(int[] parents, int x){
while(x!=parents[x]){
x=parents[x];
}
return x;
}
}
👍1