// 1971. Find if Path Exists in Graph
class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
UnionFind uf = new UnionFind(n);
for (int[] edge : edges) {
uf.union(edge[0], edge[1]);
}
return uf.find(source) == uf.find(destination);
}
}
class UnionFind {
int[] parents;
public UnionFind(int n) {
parents = new int[n];
for (int i = 0; i < n; ++i) {
parents[i] = i;
}
}
int find(int son) {
if (parents[son] == son) {
return son;
}
parents[son] = find(parents[son]);
return parents[son];
}
void union(int a, int b) {
int parentOfA = find(a);
int parentOfB = find(b);
if (parentOfA != parentOfB) {
parents[parentOfA] = parentOfB;
}
}
}
学习笔记:
这是一道简单题,入门的图题。
宽搜深搜都能用,但我前几天并查集生疏了,今天就当练习默写并查集了。
今天我把最后一句parents[parentOfA] = parentOfB;写成了parents[a] = parentOfB;闹了个大乌龙,答错了。