-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidPath.cpp
More file actions
39 lines (39 loc) · 995 Bytes
/
validPath.cpp
File metadata and controls
39 lines (39 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
class UnionFind {
private:
vector<int> p, rank;
public:
UnionFind(int n): p(n), rank(n, 1) {
std::iota(p.begin(), p.end(), 0);
}
int find(int a) {
int t = a;
while (p[t] != t) {
t = p[t];
}
while (p[a] != a) {
int next = p[a];
p[a] = t;
a = next;
}
return t;
}
void connect(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return;
if (rank[a] < rank[b])
std::swap(a, b);
p[b] = a;
rank[a] += rank[b];
}
};
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
UnionFind uf(n);
for (auto &v: edges) {
uf.connect(v[0], v[1]);
}
return uf.find(source) == uf.find(destination);
}
};