forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path589.connecting-graph.cpp
49 lines (43 loc) · 980 Bytes
/
589.connecting-graph.cpp
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
40
41
42
43
44
45
46
47
48
49
class ConnectingGraph {
private:
vector<int> graph;
public:
/*
* @param n: An integer
*/ConnectingGraph(int n) {
// do intialization if necessary
graph.resize(n + 1);
for (int i = 1; i < n + 1; ++i)
{
graph[i] = i;
}
}
int find(int node){
if (graph[node] == node)
{
return node;
}
graph[node] = find(graph[node]);
return graph[node];
}
/*
* @param a: An integer
* @param b: An integer
* @return: nothing
*/
void connect(int a, int b) {
// write your code here
int a_root = find(a);
int b_root = find(b);
graph[a_root] = b_root;
}
/*
* @param a: An integer
* @param b: An integer
* @return: A boolean
*/
bool query(int a, int b) {
// write your code here
return find(a) == find(b);
}
};