Skip to content

Commit

Permalink
Create C++-ConnectedComponents.cpp
Browse files Browse the repository at this point in the history
Program to find Connected Components in an undirected graph.
  • Loading branch information
LostAndFoundAgain committed Oct 2, 2020
1 parent 3d16b19 commit 9ef1dc3
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions C++-ConnectedComponents.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include<iostream>
#include<vector>
using namespace std;

vector<int>G[1000];
vector<bool>visited(1000,false);

void addedge(int u,int v)
{
G[u].push_back(v);
G[v].push_back(u);
}

void dfs(int x)
{
visited[x]=true;

for(auto& i : G[x])
{
if(visited[i]==false)
dfs(i);
}
}

int main()
{
int n,e,count=0;
cin>>n>>e;

for(int i=1;i<=e;i++)
{
int u,v;
cin>>u>>v;
addedge(u,v);
}

for(int i=1;i<=n;i++)
{
if(visited[i]==false)
{
dfs(i);
count++;
}
}

cout<<count;
}

0 comments on commit 9ef1dc3

Please sign in to comment.