File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ // 207.✅ Course Schedule
2+
3+ class Solution
4+ {
5+ public:
6+ // cycle detection // topological sort
7+ bool isCycle (int sv, vector<int > adj[], vector<int > &visited)
8+ {
9+ if (visited[sv] == 2 )
10+ return true ;
11+
12+ visited[sv] = 2 ;
13+
14+ for (auto itr : adj[sv])
15+ {
16+ if (visited[itr] != 1 )
17+ if (isCycle (itr, adj, visited))
18+ return true ;
19+ }
20+ visited[sv] = 1 ;
21+ return false ;
22+ }
23+
24+ bool canFinish (int numCourses, vector<vector<int >> &prerequisites)
25+ {
26+ vector<int > adj[numCourses];
27+
28+ for (auto edge : prerequisites)
29+ {
30+ adj[edge[1 ]].push_back (edge[0 ]);
31+ }
32+
33+ vector<int > visited (numCourses, false );
34+
35+ for (int i = 0 ; i < numCourses; ++i)
36+ {
37+ if (isCycle (i, adj, visited))
38+ return false ;
39+ }
40+ return true ;
41+ }
42+ };
You can’t perform that action at this time.
0 commit comments