Java 模板
public class UnionFindSet {// 节点数private int N = 1005;// 每个节点的父节点private int[] father = new int[N];/*** 并查集初始化*/public void init() {for (int i = 0; i < N; i++) father[i] = i;}/*** 查询节点的父节点下标(路径压缩)* @param u 待查询父节点的下标* @return 父节点下标*/public int find(int u) {return u == father[u] ? u : (father[u] = find(father[u]));}/*** 判断两个节点是否属于同一个集合,即他们的父节点是否相同* @param u 节点一* @param v 节点二* @return 输入的两个节点是否属于同一个集合,是=true,否=false*/public boolean isSame(int u, int v) {u = find(u);v = find(v);return u == v;}/*** 将边 u <- v 加入集合* @param u 待加入边的父节点* @param v 待加入边的子节点*/public void join(int u, int v) {u = find(u);v = find(v);if (u == v) return;father[v] = u;}
}
题目
1971. 寻找图中是否存在路径
class Solution {private int[] father;public boolean validPath(int n, int[][] edges, int source, int destination) {father = new int[n];init();for (int i = 0; i < edges.length; i++) join(edges[i][0], edges[i][1]);return isSame(source, destination);}private void init() {for (int i = 0; i < father.length; i++) father[i] = i;}private void join(int u, int v) {u = find(u);v = find(v);if (u == v) return;father[v] = u;}private int find (int u) {return u == father[u] ? u : (father[u] = find(father[u]));}private boolean isSame (int u, int v) {u = find(u);v = find(v);return u == v;}
}
更多并查集相关题目
684. 冗余连接
685. 冗余连接 II