Error in code for detecting cycle in a directed graph

when i try the following code

    {
        visited[src]=1;
        order[src]=1;
        
        for(auto it:adj[src])
        {
            if(!visited[it])
            {
            if(check(v,adj,visited,order,it))
            return true;
            }
            else{
                if(order[it])
                return true;
            }
        }
        order[src]=false;
        return false;
    }
    bool isCyclic(int v, vector<int> adj[]) {
       // code here
       vector<bool> visited(v,false);
       vector<bool> order(v,false);
       
       for(int i=0;i<v;i++)
        {
         if(!visited[i])
         {
          if(check(v,adj,visited,order,i))
           return true;
         }
        }
       return false;
    }```

i get correct answer but when i replace the line

 if(check(v,adj,visited,order,i))
           return true;

by

return check(v,adj,visited,order,i);

i get wrong answer.I have tried dry running it but still can’t figure out the problem.Can someone pls help me?

Well, you are introducing functional changes. Because

return check(v,adj,visited,order,i);

is equivalent to:

if(check(v,adj,visited,order,i))
           return true;
else
           return false;

Please note the extra “return false”, which wasn’t present in the original code.

1 Like

thanks for answering.I tried dry running again after seeing your answer and was able to understand the mistake