-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find_Connected_component.cpp
82 lines (66 loc) · 1.32 KB
/
Find_Connected_component.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<bits/stdc++.h>
using namespace std;
vector<list<int>> graph;
int v;
void addEdge(int src,int dstn,bool bidrn = true){
graph[src].push_back(dstn);
if(bidrn){
graph[dstn].push_back(src);
}
}
void display(){
for(int i=0;i<graph.size();i++){
cout<<i<<" -> ";
for(int elem : graph[i]){
cout<<elem<<" ";
}
cout<<endl;
}
}
void DFS(int node,unordered_set<int> &s){
s.insert(node);
for(int x : graph[node]){
if(s.find(x) == s.end()){
DFS(x,s);
}
}
}
void BFS(int node,unordered_set<int> &s){
queue<int> q;
q.push(node);
s.insert(node);
while(q.size()){
int temp = q.front();
q.pop();
for(int x : graph[temp]){
if(s.find(x) == s.end()){
q.push(x);
s.insert(x);
}
}
}
}
void check(){
unordered_set<int> s;
int ans = 0;
for(int i=0;i<graph.size();i++){
if(s.find(i) == s.end()){
ans++;
DFS(i,s);
}
}
cout<<"The number of connected components are : "<<ans<<endl;
}
int main(){
cin>>v;
graph.resize(v,list<int> ());
int e;
cin>>e;
while(e--){
int s,d;
cin>>s>>d;
addEdge(s,d);
}
check();
//display();
}