I want to print the number of connected components in a Graph. For this, I am using bfs traversal. I have used an map to store the adjacency list. My logic is that if vis[itr]! = true then I am incrementing the count. But the count is always coming out to be zero. Why is this so? Can anyone help me out?
#include<bits/stdc++.h>
using namespace std;
void addEdge(map<int,vector<int>>& adj, int u , int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int>bfsOfGraph(int n, map<int,vector<int>>adj, int &count)
{
vector<int>vis(n,0);
vis[0]=1;
queue<int>q;
q.push(0);
vector<int>bfs;
while(!q.empty())
{
auto node= q.front();
q.pop();
bfs.push_back(node);
for(auto it: adj[node])
{
if(!vis[it]){
count++;
vis[it]=1;0.
q.push(it);
}
}
}
cout<<"\n"<<count<<"\n";
return bfs;
}
void printGraph(int n, map<int,vector<int>>adj)
{
for(auto i : adj)
{
cout<<i.first<<" -> ";
for(auto j:i.second)
{
cout<<j<<" ";
}
cout<<"\n";
}
}
int main()
{
int n,e;
cout<<"Enter number of nodes : ";
cin>>n;
cout<<"\nEnter number of edges : ";
cin>>e;
cout<<"\nAdd edges :\n";
map<int,vector<int>>adj;
for(int i=0;i<e;i++)
{
int u,v;
cin>>u>>v;
addEdge(adj,u,v);
}
cout<<"\nPrinting Graph \n";
printGraph(n,adj);
int count=0;
bfsOfGraph(n,adj,count);
cout<<"\n"<<count;
return 0;
}