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; +}