I am making a directed Graph class. I want find if there is any Euler Cycle and update a vector with it's path accordingly. My Function some times work but others add two times the last edge of the path.
bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack, vector<int> &path) const {
if (visited[v] == false) {
// Mark the current node as visited and part of recursion stack
visited[v] = true;
recStack[v] = true;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i) {
if (!visited[*i] && isCyclicUtil(*i, visited, recStack, path)){
path.push_back(*i);
returntrue;}
elseif (recStack[*i]){
path.push_back(*i);
returntrue;}
}
}
recStack[v] = false; // remove the vertex from recursion stack
path.pop_back();
returnfalse;
}
bool Graph::cycle(vector<int> &path) const {
// Mark all the vertices as not visited and not part of recursion stack
bool *visited = newbool[V];
bool *recStack = newbool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
recStack[i] = false;
}
// Call the recursive helper function to detect cycle in different DFS trees
for (int i = 0; i < V; i++){
path.push_back(i);
if (isCyclicUtil(i, visited, recStack, path)) {
reverse(path.begin(),path.end());
//path.pop_back();
returntrue;
}
path.clear();
}
path.clear();
returnfalse;
}
Notice in the code that recStack contains the information about which nodes make up the cycle but not the order. If you make recStack int instead of bool and set it to the current recursion depth (with maybe -1 meaning that the vertex hasn't been visited) then you can recover the order from it and your path variable would be redundant.
@tpb thanks for your response , I didn't understood what benefit i will have if i know the depth. I thnink the problems occurs when It fails to find a path on an edge and finds it next( min depth 2)
Also I think `path.pop_back();` Causes some unexpected behavior
bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack, vector<int> &path) const {
if (visited[v] == false) {
// Mark the current node as visited and part of recursion stack
visited[v] = true;
recStack[v] = true;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i) {
if (!visited[*i]) {
path.push_back(*i);
if (isCyclicUtil(*i, visited, recStack, path))
returntrue;
}
elseif (recStack[*i])
returntrue;
}
}
recStack[v] = false; // remove the vertex from recursion stack
path.pop_back();
returnfalse;
}
My point about recStack is that if you stored the recursion depth instead of just true in it, you could use it to print the path, so path is kind of redundant.