jayati

Detect cycle in a directed graph

Nov 21st, 2023
971
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution {
  7.   private:
  8.     bool dfsCheck(int node,vector<int> adj[],int vis[],int pathVis[])
  9.     {
  10.         vis[node]=1;
  11.         pathVis[node]=1;
  12.        
  13.         for(auto i:adj[node])
  14.         {
  15.             if(!vis[i])
  16.             {
  17.                 if(dfsCheck(i,adj,vis,pathVis)==true)
  18.                 {
  19.                     return true;
  20.                 }
  21.             }
  22.             else if(pathVis[i])
  23.             {
  24.                 return true;
  25.             }
  26.         }
  27.         pathVis[node]=0;
  28.         return false;
  29.     }
  30.   public:
  31.     // Function to detect cycle in a directed graph
  32.     bool isCyclic(int V, vector<int> adj[]) {
  33.         // code here
  34.         int vis[V]={0};
  35.         int pathVis[V]={0};
  36.        
  37.         for(int i=0;i<V;i++)
  38.         {
  39.             if(!vis[i])
  40.             {
  41.                 if(dfsCheck(i,adj,vis,pathVis)==true)
  42.                 {
  43.                     return true;
  44.                 }
  45.             }
  46.         }
  47.         return false;
  48.     }
  49. };
  50.  
  51. //{ Driver Code Starts.
  52.  
  53. int main() {
  54.  
  55.     int t;
  56.     cin >> t;
  57.     while (t--) {
  58.         int V, E;
  59.         cin >> V >> E;
  60.  
  61.         vector<int> adj[V];
  62.  
  63.         for (int i = 0; i < E; i++) {
  64.             int u, v;
  65.             cin >> u >> v;
  66.             adj[u].push_back(v);
  67.         }
  68.  
  69.         Solution obj;
  70.         cout << obj.isCyclic(V, adj) << "\n";
  71.     }
  72.  
  73.     return 0;
  74. }
  75.  
  76. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment