forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1319.cpp
More file actions
30 lines (27 loc) · 645 Bytes
/
Copy path1319.cpp
File metadata and controls
30 lines (27 loc) · 645 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
class Solution
{
public:
int makeConnected(int n, vector<vector<int>>& connections)
{
if (connections.size() < n - 1) return -1;
parent = vector<int>(n);
for (int i = 0; i < n; i++) parent[i] = i;
int res = n;
for (auto& it : connections)
{
int x = find(it[0]), y = find(it[1]);
if (x != y)
{
parent[x] = y, res--;
}
}
return res - 1;
}
private:
vector<int> parent;
int find(int x)
{
if (x != parent[x]) parent[x] = find(parent[x]);
return parent[x];
}
};