diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp new file mode 100644 index 000000000..4df4fb7c6 --- /dev/null +++ b/graph/connected_components.cpp @@ -0,0 +1,61 @@ +#include +#include + +using namespace std; + +class graph +{ + private: + vector> adj; + int cc; + void dfs(); + void explore(int, vector&); + public: + graph(int n): adj(n,vector()), cc(0) {} + void addEdge(int,int); + int getConnectedComponents() + { + dfs(); + return cc; + } +}; + +void graph::addEdge(int u, int v) +{ + adj[u-1].push_back(v-1); + adj[v-1].push_back(u-1); +} + +void graph::dfs() +{ + int n = adj.size(); + vector visited(n,false); + + for(int i = 0;i &visited) +{ + visited[u] = true; + for(auto v : adj[u]) + { + if(!visited[v]) + explore(v,visited); + } +} + +int main() +{ + graph g(4); + g.addEdge(1,2); + g.addEdge(3,2); + cout<