有一个具有 n
个顶点的 双向 图,其中每个顶点标记从 0
到 n - 1
(包含 0
和 n - 1
)。图中的边用一个二维整数数组 edges
表示,其中 edges[i] = [ui, vi]
表示顶点 ui
和顶点 vi
之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。
请你确定是否存在从顶点 source
开始,到顶点 destination
结束的 有效路径 。
class Solution {
int[] fa;
public boolean validPath(int n, int[][] edges, int source, int destination) {
//并查集
if(source==destination) return true;
fa=new int[n];
for(int i=0;i<n;i++){
fa[i]=i;
}
for(int edge[]:edges){
union(edge[0],edge[1]);
}
return find(source)==find(destination);
}
public void union(int x,int y){
int rootx=find(x);
int rooty=find(y);
fa[rootx]=rooty;
}
public int find(int i){
if(i!=fa[i]){
fa[i]=find(fa[i]);
}
return fa[i];
}
}