Advertisement
vaibhav1906

Course schedule

Jan 11th, 2022
1,189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int dfs(vector<int> *a,vector<int> &vis,vector<int> &rec,int x)
  4.     {
  5.         vis[x]=1;
  6.         rec[x]=1;
  7.         for(int i:a[x])
  8.         {
  9.             if(vis[i]==1 && rec[i]==1)
  10.                 return 1;
  11.             if(vis[i]==0 && dfs(a,vis,rec,i))
  12.                 return 1;
  13.         }
  14.         rec[x]=0;
  15.         return 0;
  16.     }
  17.     bool canFinish(int n, vector<vector<int>>& e) {
  18.         vector<int> a[n];
  19.         for(int i=0;i<e.size();i++)
  20.         {
  21.             a[e[i][0]].push_back(e[i][1]);
  22.         }
  23.         vector<int> vis(n,0);
  24.         vector<int> rec(n,0);
  25.         for(int i=0;i<n;i++)
  26.         {
  27.             if(vis[i]==0)
  28.             {
  29.                 int x=dfs(a,vis,rec,i);
  30.                 if(x==1)
  31.                     return 0;
  32.             }
  33.         }
  34.         return 1;
  35.     }
  36. };
  37. // to complete all courses there shouldn't be any cycle
  38. // if there is a cycle then we cannot complete all course
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement