From b8fb3a9135da8b08dc4ab95781035bae65ff7215 Mon Sep 17 00:00:00 2001 From: sakshamkhowala <91794323+sakshamkhowala@users.noreply.github.com> Date: Sat, 2 Oct 2021 21:10:32 +0530 Subject: [PATCH] Cycle Detection Directed Graphs --- Algorithms/CycleDetectionDirected.cpp | 67 +++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Algorithms/CycleDetectionDirected.cpp diff --git a/Algorithms/CycleDetectionDirected.cpp b/Algorithms/CycleDetectionDirected.cpp new file mode 100644 index 0000000..6e9da12 --- /dev/null +++ b/Algorithms/CycleDetectionDirected.cpp @@ -0,0 +1,67 @@ +#include +using namespace std; + +class Solution +{ + public: + bool cycleDFS(int node,vector adj[], vector &vis, vector &dfsvis) + { + vis[node]=1; + dfsvis[node]=1; + + for(auto it:adj[node]) + { + if(!vis[it]) + { + if(cycleDFS(it,adj,vis,dfsvis))return true; + } + else if(dfsvis[it]) + return true; + } + dfsvis[node]=0; + return false; + } + public: + //Function to detect cycle in a directed graph. + bool isCyclic(int V, vector adj[]) + { + vectorvis(V,0); + vectordfsvis(V,0); + for(int i=0;i> t; + while(t--) + { + int V, E; + cin >> V >> E; + + vector adj[V]; + + for(int i = 0; i < E; i++) + { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + } + + Solution obj; + cout << obj.isCyclic(V, adj) << "\n"; + } + + return 0; +}