Beautiful vertices

#include<bits/stdc++.h>
using namespace std;
int n;

class Graph{
map<int,list > m;

public:
	Graph()
	{
		
	}
	void addNode(int u,int v,int bidir=true)
	{
		m[u].push_back(v);
		if(bidir)
		{
			m[v].push_back(u);
		}
	}
	
	int dfsUtil(int src,bool *visited,int *count,int &ans)
	{
		visited[src]=true;
		count[src]=1;
		
		for(auto x:m[src])
		{
			if(!visited[x])
			{
				count[src]+=dfsUtil(x,visited,count,ans);
				
				int num=count[src];
				
				if(num-1>n-num && n-num>0)
				ans++;
				
			}
		}
		return count[src];
	}
	int dfs()
	{
		bool visited[n+1]{0};
		int count[n+1]{0};
		int ans=0;
		
		dfsUtil(1,visited,count,ans);
		return ans;
	}

};
int main()
{
Graph g;
int m;
cin>>n>>m;
while(m–)
{
int x,y;
cin>>x>>y;
g.addNode(x,y);
}
cout<<g.dfs();
}

what is error in this code?

Hi @Ankit003
There’s a logical error. You have called dfsUtil for 1 only. Assume an example in which list of 1 is empty. Then your function just returns 0 without traversing other nodes of the graph. So we shall maintain a visited map for all the nodes and call dfsUtil for unvisited nodes.
Hope this helps :wink:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.