From e9505085f8cd822f96ecb8b04284740cbab55ee8 Mon Sep 17 00:00:00 2001 From: Atishay Jain <69712595+atishayzn@users.noreply.github.com> Date: Thu, 7 Oct 2021 00:36:59 +0530 Subject: [PATCH] Detect cycle in a directed graph --- Detect-cycle-in-a-directed-graph.cpp | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Detect-cycle-in-a-directed-graph.cpp 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