1

I am trying to find the number of nodes in a cycle of a graph. I am using recursion and DFS to calculate the number of nodes in all the cycles of the graph.Here is the calculating function in C++.

int iscyclic(int node,bool visited[],bool rec[],vector<int>g[])
{
    if(!visited[node])
{
    visited[node] = true;
    rec[node] = true;
    vector<int>::iterator it;
    for(it=g[node].begin();it!=g[node].end();it++)
    {
        if(!visited[*it] && iscyclic(*it,visited,rec,g))
        {
            kount++;
        }
        else if(rec[*it])
            kount++;
    }
}
rec[node] = false;
return kount;
}

The Visited and rec array are set to false by default and kount has been globally set as 0. The kount is supposed to calculate the number of nodes in a cycle of the directed graph.However there are cases where the answer is wrong. Please help.I Have recently started learning graph theory.

soumya dubey
  • 63
  • 1
  • 1
  • 10

1 Answers1

0

You should not do this:

else if(rec[*it])
   kount++;

Also, you need to make sure that the starting node (the one you call the function with) is really part of a cycle.

Third thing - you return kcount as result of your function, when you atually should return true or false based on the fact whether you encountered a cycle in this branch or not.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Okay , but on returning boolean values i would get the result that weather there exists a cycle or not but i am interested in finding the number of nodes present in that cycle – soumya dubey Aug 07 '16 at 08:48
  • Nope. You either way obtain the result in `kcount`. It is global and you can always access it. Whether you found a cycle or not, on the other hand, is important result telling you whether the currently processed branch of the recursion triggered successful result or not. In case of success you should discontinue considering the other branches – Boris Strandjev Aug 08 '16 at 05:12