-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCourse_Schedule_II.cpp
More file actions
63 lines (47 loc) · 1.58 KB
/
Course_Schedule_II.cpp
File metadata and controls
63 lines (47 loc) · 1.58 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
58
59
60
61
62
63
// https://leetcode.com/problems/course-schedule-ii/
/*
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
*/
class Solution {
public:
vector < vector < int> > adj;
vector <int> ans, visited, color;
bool isCyclic;
void dfs(int v)
{
color[v] = 1;
visited[v] = 1;
for(auto u : adj[v])
{
if(color[u] == 1)
isCyclic = true;
if(!visited[u])
dfs(u);
}
color[v] = 2;
ans.push_back(v);
}
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites)
{
adj.resize(numCourses);
for(auto v : prerequisites)
adj[v[0]].push_back(v[1]);
visited.assign(numCourses, 0);
color.assign(numCourses, 0);
ans.clear();
isCyclic = false;
for(int i = 0; i < numCourses; i++)
{
if(!visited[i])
dfs(i);
}
vector <int> emp;
if(isCyclic)
return emp;
// reverse(ans.begin(), ans.end());
return ans;
}
};