-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path364.cpp
61 lines (49 loc) · 1.24 KB
/
364.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
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
void addEdge(vector<pair<int,int>> g[],int u,int v,int w=1){
g[u].push_back(make_pair(v,w));
g[v].push_back(make_pair(u,w));
}
void display(vector<pair<int,int>> g[],int V){
for(int i=0;i<V;i++){
for(int j=0;j<g[i].size();j++){
cout<<i<<" to "<<g[i][j].first<<" weight is : "<<g[i][j].second<<"\n";
}
}
}
void bfstraversal(vector<pair<int,int>> g[],int u,vector<bool> &visited){
queue<int> q;
q.push(u);
visited[u]=true;
while(!q.empty()){
int x=q.front();
q.pop();
cout<<x<<" ";
for(auto it:g[x]){
if(!visited[it.first]) {
visited[it.first]=true;
q.push(it.first);
}
}
}
}
int bfs(vector<pair<int,int>> g[],int V){
vector<bool> visited(V,false);
int c=0;
for(int u=0;u<V;u++){
if(!visited[u]) {
bfstraversal(g,u,visited);
c++;
}
}
return c-1;
}
int makeConnected(int n, vector<vector<int>>& connections) {
if(connections.size()<n-1) return -1;
vector<pair<int,int>> g[n];
for(int i=0;i<connections.size();i++){
addEdge(g,connections[i][0],connections[i][1]);
}
return bfs(g,n);
}
};