并查集(Union Find)是图中高效查询的一种方法
话不多说,开始实战!
leetcode1971 寻找两个节点是否存在路径
package 剑指offer.并查集;
import java.util.Arrays;
/**
* [一句话描述该类的功能]
*
* @author : [61692]
* @version : [v1.0]
* @createTime : [2022/9/4 22:21]
*/
public class leetcode1971寻找图中是否存在路径 {
class Solution {
//定义根节点数组 用于存储节点所对应的根节点
int[] root;
public boolean validPath(int n, int[][] edges, int source, int destination) {
root = new int[n];
Arrays.fill(root,-1);
//对每个edge两个节点都合并到一个“集合”
for(int[] edge : edges){
union(edge[0],edge[1]);
}
//如果两个节点会存在路径,那么其根节点一定是一个
return find(source) == find(destination);
}
//查找(一直找节点的根节点)
public int find(int x){
int xroot = x;
while(root[xroot] != -1){
xroot = root[xroot];
}
return xroot;
}
//合并两个集合
public void union(int x, int y){
int xroot = find(x);
int yroot = find(y);
if(xroot != yroot){
root[xroot] = yroot;
}
}
}
}
相同的练习题还有:
leetcode 200 岛屿数量
leetcode 547 朋友圈