Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect cycle in a directed graph #1717

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Detect-cycle-in-a-directed-graph.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution
{ public:
bool dfsCycle(int i,vector<int>adj[],int vis[],int dfsVis[]){
vis[i]=1;
dfsVis[i]=1;
for(auto u :adj[i]){
if(!vis[u]){
if(dfsCycle(u,adj,vis,dfsVis))return true;
}
else if(dfsVis[u])return true;
}
dfsVis[i]=0;
return false;
}
public:
//Function to detect cycle in a directed graph.
bool isCyclic(int V, vector<int> adj[])
{
int vis[V];
int dfsVis[V];
memset(vis,0,sizeof(vis));
memset(dfsVis,0,sizeof(dfsVis));
for(int i=0;i<V;i++){
if(!vis[i])
if(dfsCycle(i,adj,vis,dfsVis))return true;
}
return false;
}
};