diff --git a/C++-ConnectedComponents.cpp b/C++-ConnectedComponents.cpp new file mode 100644 index 0000000..d26eac8 --- /dev/null +++ b/C++-ConnectedComponents.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; + +vectorG[1000]; +vectorvisited(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<