-
Notifications
You must be signed in to change notification settings - Fork 28
/
Course_Schedule_II.cpp
46 lines (44 loc) · 1.37 KB
/
Course_Schedule_II.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
class Solution {
const int white = 0;
const int grey = 1;
const int black = 2;
bool hasCycle(int node, vector<vector<int>> const& adj, vector<int>& color, vector<int>& result) {
color[node] = grey;
for(int i = 0; i < (int)adj[node].size(); ++i) {
int neigh = adj[node][i];
if(color[neigh] == grey) {
return true;
}
if(color[neigh] == white) {
if(hasCycle(neigh, adj, color, result)) {
return true;
}
}
}
color[node] = black;
result.push_back(node);
return false;
}
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
int edges = prerequisites.size();
vector<vector<int>> adj;
adj.resize(numCourses);
for(int i = 0; i < edges; ++i) {
int u = prerequisites[i].first;
int v = prerequisites[i].second;
adj[u].push_back(v);
}
vector<int> result;
vector<int> color(numCourses, white);
for(int i = 0; i < numCourses; ++i) {
if(color[i] == white) {
if(hasCycle(i, adj, color, result)) {
result = vector<int>();
return result;
}
}
}
return result;
}
};