File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ bool canFinish (int numCourses, vector<pair<int , int >>& prerequisites) {
4
+ vector<vector<int >> inGraph (numCourses, vector<int >());
5
+ vector<vector<int >> outGraph (numCourses, vector<int >());
6
+ vector<bool > okCourse (numCourses, true );
7
+
8
+ for (auto && prerequisite : prerequisites) {
9
+ outGraph[prerequisite.first ].push_back (prerequisite.second );
10
+ inGraph[prerequisite.second ].push_back (prerequisite.first );
11
+ okCourse[prerequisite.first ] = false ;
12
+ okCourse[prerequisite.second ] = false ;
13
+ }
14
+ while (true ) {
15
+ bool changed = false ;
16
+ for (int i = 0 ; i < numCourses; ++i) {
17
+ if (okCourse[i]) continue ;
18
+
19
+ if (inGraph[i].empty ()) {
20
+ okCourse[i] = true ;
21
+ for (int j = 0 ; j < outGraph[i].size (); ++j) {
22
+ changed = true ;
23
+ auto it = find (std::begin (inGraph[outGraph[i][j]]), std::end (inGraph[outGraph[i][j]]), i);
24
+ if (it != std::end (inGraph[outGraph[i][j]])) {
25
+ inGraph[outGraph[i][j]].erase (it);
26
+ }
27
+ }
28
+ }
29
+ }
30
+ if (!changed) {
31
+ break ;
32
+ }
33
+ }
34
+ for (int i = 0 ; i < numCourses; ++i) {
35
+ if (!okCourse[i]) return false ;
36
+ }
37
+ return true ;
38
+ }
39
+ };
You can’t perform that action at this time.
0 commit comments