-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCourse_Schedule.cpp
More file actions
57 lines (49 loc) · 1.14 KB
/
Course_Schedule.cpp
File metadata and controls
57 lines (49 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// https://leetcode.com/problems/course-schedule/
class Solution {
public:
vector < vector < int> > adj;
vector <int> parent, color;
int cycle_start, n;
bool dfs(int v)
{
color[v] = 1;
for(int u : adj[v])
{
if(color[u] == 0)
{
parent[u] = v;
if(dfs(u))
return true;
}
else if(color[u] == 1)
{
cycle_start = u;
return true;
}
}
color[v] = 2;
return false;
}
bool isCyclic()
{
color.assign(n, 0);
parent.assign(n, -1);
cycle_start = -1;
for(int v = 0; v < n; v++)
{
if(dfs(v))
break;
}
if(cycle_start == -1)
return false;
return true;
}
bool canFinish(int numCourses, vector<vector<int>>& prerequisites)
{
n = numCourses;
adj.resize(n);
for(auto v : prerequisites)
adj[v[1]].push_back(v[0]);
return !isCyclic();
}
};