Plz correct this
If it is for a directed graph …
#include<iostream>
#include<list>
using namespace std;
class graph
{
int v;
list<int>*l;
public:
graph(int v)
{ this->v=v;
l=new list<int>[v];
}
void addedge(int x,int y)
{
l[x].push_back(y);
//l[y].push_back(x);
}
bool cycle_helper(int node,bool visited[],bool stacks[])
{
visited[node]=true;
stacks[node]=true;
for(auto nbr:l[node])
{
if(stacks[nbr]==true)
return true;
if(visited[nbr]==false)
{
bool cycle_mila=cycle_helper(nbr,visited,stacks);
if(cycle_mila==true)
return true;
}
}
stacks[node]=false;
return false;
}
bool cycle()
{
bool *visited=new bool [v];
bool *stacks=new bool[v];
for(int i=0;i<v;i++)
visited[i]=stacks[i]=false;
int ans = 0;
//For Various connected components
for(int i=0;i<v;i++){
if(visited[i]) continue;
ans|=cycle_helper(i,visited,stacks);
}
return ans;
}
};
int main()
{
graph g(7);
g.addedge(0,1);
g.addedge(1,2);
g.addedge(2,3); g.addedge(4,5);
g.addedge(3,4);
// g.addedge(4,2);
g.addedge(1,5);
if(g.cycle())
cout<<"yes present";
else
cout<<"no";
}