I am new to C++ STL and have started Graph Theory recently. After referring to https://www.geeksforgeeks.org/connected-components-in-an-undirected-graph/, I can count the number of connected components in an undirected, unweighted graph using DFS as:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int connected=0, temp1, temp2,n, p;
void DFS(int start, vector<int> v[],vector<int> &visited) {
visited[start] = 1;
for(int i= 0; i<v[start].size(); ++i) {
if(visited[v[start][i]] == 0)
DFS(v[start][i], v, visited);
}
}
int main() {
cin>>n>>p; // number of vertices and edges
vector<int> v[n+1], visited(n+1,0);
for(int i=0; i<p; ++i) {
cin>>temp1>>temp2;
v[temp1].push_back(temp2);
v[temp2].push_back(temp1);
}
connected = 0;
for(int i=1;i<=n;++i) {
if(visited[i] == 0 ) {
connected++;
DFS(i,v,visited);
}
}
cout<<connected<<endl;
return 0;
}
But how do we count the total number of nodes in each component?
For example: In this graph, see image there are 3 connected components, with no. of nodes being 3, 2 , and 1 respectively.