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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.