Count number of nodes in each connected part of an undirected unweighted graph code example
Example: Count number of nodes in each connected part of an undirected unweighted graph
void DFS(int start, vector<int> v[],vector<int> &visited, int &count)
{
visited[start] = 1;
count++;
for(int i= 0; i<v[start].size(); ++i)
{
if(visited[v[start][i]] == 0)
DFS(v[start][i], v, visited);
}
}
---------------------------------------------------
for(int i=1;i<=n;++i)
{
if(visited[i] == 0 )
{
connected++;
int count=0;
DFS(i,v,visited,count);
cout<<"This component has "<<count<<" nodes"<<"\n";
}
}