-
Notifications
You must be signed in to change notification settings - Fork 128
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Program to find Connected Components in an undirected graph.
- Loading branch information
1 parent
3d16b19
commit 9ef1dc3
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |