Given a list of courses you have to take and a list of prerequisites, return the order in which you have to take the courses. If it is not possible to take all the courses return an empty list.
Show Answer
C++
class Solution {
public:
vector<int> order;
vector<int> graph[2005];
int color[2005] = {0};
bool dfs(int u){
color[u] = 1;
for(auto v : graph[u]){
if( color[v] == 1 ) return false;
if( color[v] == 2 ) continue;
bool possible = dfs(v);
if( !possible ) return false;
}
color[u] = 2;
order.push_back(u);
return true;
}
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
for(auto prerequisite : prerequisites){
graph[prerequisite[1]].push_back(prerequisite[0]);
}
for(int i = 0; i < numCourses; i++){
if( color[i] == 0 ) {
bool possible = dfs(i);
if( !possible ) return vector<int>{};
}
}
reverse(order.begin(), order.end());
return order;
}
};