Advertisement
Iam_Sandeep

check cycle directed graph : graph coloring method

Jun 6th, 2021
1,235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. /*
  2. 0-------------->unvisited
  3. 1-------------->processing in dfs
  4. 2-------------->processed
  5. */
  6.  
  7. class Solution {
  8.     bool cycle(int src,map<int,vector<int>> &adj,vector<int> &vis){
  9.         if (vis[src]==1)
  10.             return true;//you came back to ancestor node......cycle here
  11.         vis[src]=1;//make it as processing
  12.         for(auto node:adj[src]){
  13.             if (vis[node]!=2){
  14.                if (cycle(node,adj,vis))
  15.                    return true;
  16.             }
  17.         }
  18.         vis[src]=2;//make it as processed
  19.         return false;
  20.     }
  21.    
  22. public:
  23.     bool canFinish(int n, vector<vector<int>>& p) {
  24.         vector<int> vis(n,0);
  25.         map<int,vector<int>> adj;
  26.         for(auto x:p)
  27.             adj[x[0]].push_back(x[1]);
  28.        
  29.         for(int i=0;i<n;++i)
  30.             if (vis[i]==0){
  31.                 if (cycle(i,adj,vis))
  32.                     return false;
  33.             }
  34.         return true;
  35.        
  36.     }
  37. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement