

给出一个无向图,顶点数,边(顶点-顶点),
问顶点source是否能和顶点destination连通(它们之间是否存在路径)。
思路:
以往的找路径一般是建立邻接链表,然后用dfs的方法找。
因为这里不需要具体路径,只需要看source和destination在不在一个group即可。
所以用union find.
初始化时每个node的parent是它自己,然后利用边更新parent,
这里是把edge[1]的root更新成edge[0]的root,
注意一定是parent[root]更新而不是parent[node]本身更新。
最后看source和destination的root是否相同即可。
class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
int[] parent = new int[n];
for(int i = 0; i < n; i++) {
parent[i] = i;
}
//union
for(int[] edge : edges) {
int p1 = findRoot(parent, edge[0]);
int p2 = findRoot(parent, edge[1]);
if(p1 != p2) parent[p2] = p1;
}
return findRoot(parent,source)==findRoot(parent,destination);
}
int findRoot(int[] parent, int node) {
int p = node;
while(parent[p] != p) {
p = parent[p];
parent[p] = parent[parent[p]]; //达到log时间搜索的效果
}
return p;
}
}
该博客介绍了如何利用并查集(Union-Find)数据结构解决无向图中判断两个顶点source和destination之间是否存在路径的问题。通过初始化每个顶点为自己的根节点,然后根据边的信息更新父节点,最后比较source和destination的根节点是否相同来确定连通性。这种方法避免了深度优先搜索寻找具体路径,提高了效率。
647

被折叠的 条评论
为什么被折叠?



