-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0210.cpp
More file actions
48 lines (40 loc) · 962 Bytes
/
0210.cpp
File metadata and controls
48 lines (40 loc) · 962 Bytes
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
class Solution {
bool dfs(int node, vector<int> &vis, stack<int> &st,
vector<vector<int>> &adjList) {
if (vis[node] == 1)
return false;
if (vis[node] == 2)
return true;
vis[node] = 1;
for (int neighbor : adjList[node]) {
if (!dfs(neighbor, vis, st, adjList)) {
return false;
}
}
vis[node] = 2;
st.push(node);
return true;
}
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites) {
vector<vector<int>> adjList(numCourses);
for (auto &pre : prerequisites) {
adjList[pre[1]].push_back(pre[0]);
}
vector<int> vis(numCourses, 0);
stack<int> st;
for (int i = 0; i < numCourses; i++) {
if (vis[i] == 0) {
if (!dfs(i, vis, st, adjList)) {
return {};
}
}
}
vector<int> topo;
while (!st.empty()) {
topo.push_back(st.top());
st.pop();
}
return topo;
}
};