Advertisement
knakul853

Untitled

Jul 24th, 2020
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. class Solution {
  2.    
  3.    
  4. public:
  5.     bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
  6.        
  7.         int n = (int)prerequisites.size();
  8.         vector<int>state(numCourses, 0);
  9.         vector<vector<int>>g(numCourses);
  10.        
  11.         for(int i=0;i<n;i++)
  12.         {
  13.             g[prerequisites[i][1]].push_back(prerequisites[i][0]);
  14.         }
  15.        
  16.        
  17.         for(int i=0;i<numCourses;i++)
  18.         {
  19.             if(state[i] == 0)
  20.             {
  21.                 if( dfs( i, g, state )) return false;
  22.             }
  23.         }
  24.        
  25.         return true;
  26.        
  27.     }
  28.    
  29.     bool dfs(int node,vector<vector<int>>&g, vector<int>&state )
  30.     {
  31.         state[node] = 1;
  32.         bool hasCylcle = false;
  33.        
  34.         for( int neighbour : g[node] )
  35.         {
  36.             if( state[neighbour] == 0 )
  37.             {
  38.                hasCylcle|= dfs(neighbour,g, state);
  39.             }
  40.             else if(state[neighbour] == 1)
  41.             {
  42.                 hasCylcle = true;
  43.             }
  44.         }
  45.        
  46.         state[node] = 2;
  47.         return hasCylcle;
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement