-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathBFSsolution.cpp
More file actions
40 lines (36 loc) · 989 Bytes
/
BFSsolution.cpp
File metadata and controls
40 lines (36 loc) · 989 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
40
class Solution {
public:
int makeConnected(int n, vector<vector<int>>& c) {
int edges = c.size();;
if( edges < n - 1 ){
return -1;
}
vector<int> adj[n];
vector<int> vis(n, 0);
for( int i=0; i < c.size(); i++ ) {
adj[ c[i][0] ].push_back( c[i][1] );
adj[ c[i][1] ].push_back( c[i][0] );
}
queue<int> q;
int count = 0;
for(int i = 0; i<n; i++) {
if( !vis[i] ) {
count++;
vis[i] = 1;
q.push(i);
while(!q.empty()){
int node = q.front();
q.pop();
for(auto x : adj[node]) {
if( !vis[x] ) {
q.push(x);
vis[x] = 1;
}
}
}
}
}
count--;
return count;
}
};