diff --git a/Detect-cycle-in-a-directed-graph.cpp b/Detect-cycle-in-a-directed-graph.cpp new file mode 100644 index 000000000..c448ba0ca --- /dev/null +++ b/Detect-cycle-in-a-directed-graph.cpp @@ -0,0 +1,29 @@ +class Solution +{ public: + bool dfsCycle(int i,vectoradj[],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 adj[]) + { + int vis[V]; + int dfsVis[V]; + memset(vis,0,sizeof(vis)); + memset(dfsVis,0,sizeof(dfsVis)); + for(int i=0;i