-
Notifications
You must be signed in to change notification settings - Fork 0
/
CourseScheduleII.cpp
57 lines (44 loc) · 1.42 KB
/
CourseScheduleII.cpp
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
class Solution {
public:
bool topo_DFS(int v, vector<bool>* visited, vector<bool>* curr_visited,
vector<int>* order, vector<int>* graph) {
(*visited)[v] = true;
(*curr_visited)[v] = true;
for (int i = 0; i < graph[v].size(); i++) {
int u = graph[v][i];
if ((*curr_visited)[u]) {
return false;
}
if (!(*visited)[u]) {
if (!topo_DFS(u, visited, curr_visited, order, graph)) {
return false;
}
}
}
(*curr_visited)[v] = false;
order->push_back(v);
return true;
}
vector<int> topo(int n, vector<int>* graph) {
vector<bool> visited(n);
vector<bool> curr_visited(n);
vector<int> order;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
if (!topo_DFS(i, &visited, &curr_visited, &order, graph)) {
return {};
}
}
}
return order;
}
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<int>* graph = new vector<int>[numCourses];
for (int i = 0; i < prerequisites.size(); i++) {
int a_i = prerequisites[i][0];
int b_i = prerequisites[i][1];
graph[a_i].push_back(b_i);
}
return topo(numCourses, graph);
}
};