-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConnectedComponent.cpp
More file actions
56 lines (53 loc) · 1.11 KB
/
ConnectedComponent.cpp
File metadata and controls
56 lines (53 loc) · 1.11 KB
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
#include<bits/stdc++.h>
using namespace std;
class graph
{
int V;
list<int>*adj;
public:
graph(int V)
{
this->V = V;
this->adj = new list<int>[this->V];
}
void addedge(int u,int v)
{
this->adj[u].push_back(v);
this->adj[v].push_back(u);
}
void DFSHelper(vector<bool>&visited,int source)
{
visited[source]=true;
cout<<source<<" ";
for(auto itr= this->adj[source].begin();itr!=this->adj[source].end(); itr++)
{
if(!visited[*itr])
{
DFSHelper(visited,*itr);
}
}
}
void DFS()
{
vector<bool>visited(this->V,false);
int count = 0;
for(int v=0;v<this->V;v++)
{
if(!visited[v])
{
DFSHelper(visited,v);
cout<<"\n";
count++;
}
}
cout<<"No of connected_component: "<<count<<endl;
}
};
int main()
{
graph g(5); // 5 vertices numbered from 0 to 4
g.addedge(1, 0);
g.addedge(2, 3);
g.addedge(3, 4);
g.DFS();
}