I always end up getting Memory Limit Exceed whenever I use a graph data structure. I think there is some kind of error in my implementation, which I cannot spot. Can someone help me out with that?
I this problem I have used the same logic as given on https://www.geeksforgeeks.org/number-of-simple-cyclic-components-in-an-undirected-graph/
But I am still getting the Memory limit to exceed. So can somebody help me out?
#include<bits/stdc++.h>
using namespace std;
vector<int> p; //This vector keeps the curr component that is fetched using dfs.
void dfs(vector<vector<int> > g,bool arr[],int i)
{
arr[i]=true;
p.push_back(i);
for(auto it=g[i].begin();it!=g[i].end();it++)
{
if(!arr[*it])
{
dfs(g,arr,(*it));
}
}
}
int main()
{
int n,m;
cin >> n >> m;
vector<vector<int> > G(n+1);
for(int i=0;i<m;i++)
{
int x,y;
cin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
bool vis[n+1];
memset(vis,false,sizeof(vis));
int count = 0;
for(int i=1;i<=n;i++)
{
vector<int> temp;
if(!vis[i])
{
bool flag=true;
dfs(G,vis,i);
for(int i=0;i<p.size();i++)
{
if(G[p[i]].size()!=2) //Checking if degree is 2 or not!
{
flag=false;
break;
}
}
if(flag)
{
count++;
}
p.clear();
}
}
cout << count << "\n";
return 0;
}