1
- class Solution {
2
- public:
3
- bool canFinish (int numCourses, vector<vector<int >>& prerequisites) {
1
+ // class Solution {
2
+ // public:
3
+ // bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
4
4
5
- vector<vector<int >> graph (numCourses);
6
- vector<int > indegree (numCourses,0 );
5
+ // vector<vector<int>> graph(numCourses);
6
+ // vector<int> indegree(numCourses,0);
7
7
8
- for (auto edge : prerequisites)
9
- {
10
- graph[edge[1 ]].push_back (edge[0 ]);
11
- indegree[edge[0 ]]++;
12
- }
8
+ // for(auto edge : prerequisites)
9
+ // {
10
+ // graph[edge[1]].push_back(edge[0]);
11
+ // indegree[edge[0]]++;
12
+ // }
13
13
14
- queue<int > Q;
14
+ // queue<int> Q;
15
15
16
- for (int i = 0 ;i < numCourses;i++)
17
- if (indegree[i] == 0 )
18
- Q.push (i);
16
+ // for(int i = 0;i < numCourses;i++)
17
+ // if(indegree[i] == 0)
18
+ // Q.push(i);
19
19
20
- int counter = 0 ;
21
- while (!Q.empty ())
22
- {
23
- int u = Q.front ();
24
- Q.pop ();
20
+ // int counter = 0;
21
+ // while(!Q.empty())
22
+ // {
23
+ // int u = Q.front();
24
+ // Q.pop();
25
25
26
- counter++;
27
- for (auto v : graph[u])
28
- {
29
- if (--indegree[v] == 0 )
30
- Q.push (v);
26
+ // counter++;
27
+ // for(auto v : graph[u])
28
+ // {
29
+ // if(--indegree[v] == 0)
30
+ // Q.push(v);
31
+ // }
32
+ // }
33
+ // return counter == numCourses;
34
+ // }
35
+ // };
36
+
37
+ class Solution {
38
+ public:
39
+ bool isCyclic (vector<int > pre[], vector<int > &visited, int node) {
40
+
41
+ if (visited[node] == 1 ) return true ; // in-process already..
42
+
43
+ if (visited[node] == 0 ) { // processing unprocessed node..
44
+ visited[node] = 1 ;
45
+ for (auto child : pre[node]) {
46
+ if (isCyclic (pre, visited, child))
47
+ return true ;
48
+ }
49
+ }
50
+ visited[node] = 2 ;
51
+ return false ;
52
+ }
53
+
54
+ bool canFinish (int numCourses, vector<vector<int >>& prerequisites) {
55
+
56
+ vector<int > prereq[numCourses];
57
+ for (auto edge : prerequisites) {
58
+ prereq[edge[1 ]].push_back (edge[0 ]);
59
+ }
60
+
61
+ vector<int > visited (numCourses, 0 );
62
+ for (int i=0 ; i<numCourses; i++) {
63
+ if (isCyclic (prereq, visited, i)) {
64
+ return false ;
31
65
}
32
66
}
33
- return counter == numCourses ;
67
+ return true ;
34
68
}
35
- };
69
+ };
0 commit comments