forked from codewithshailendra/COYO-IIT-BHU
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnected Components in a Graph
58 lines (44 loc) · 974 Bytes
/
Connected Components in a Graph
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
/*
// Sample code to perform I/O:
cin >> name; // Reading input from STDIN
cout << "Hi, " << name << ".\n"; // Writing output to STDOUT
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
*/
// Write your code here
#include<bits/stdc++.h>
using namespace std;
map<int,vector<int> >mp;
map<int,bool>visited;
void dfs(int root)
{
visited[root]=true;
for(auto x:mp[root])
{
if(!visited[x])
dfs(x);
}
return;
}
int main()
{
int n,e; cin>>n>>e;
//map<int,vector<int> >mp;
//int storage[n+1];
for(int i=1;i<=e;i++)
{
int a,b; cin>>a>>b;
mp[a].push_back(b);
mp[b].push_back(a);
}
int countr=0;
for(int i=1;i<=n;i++)
{
if(!visited[i])
{
dfs(i);
countr++;
}
}
cout<<countr<<endl;
return 0;
}