# [210. Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)
# 思路
这题是`207. Course Schedule`的变体，207题要求判断是否可以完成整个课程，即判断有向图是否有环，然后我们用拓扑排序来判断是否有环。
而这题其实就是求有向图的拓扑排序，也分为BFS和DFS两种，思路和207一样的，所以这里不再赘述，可参考[207题解](https://github.com/ShusenTang/LeetCode/blob/master/solutions/207.%20Course%20Schedule.md)。

# C++
## BFS
``` C++
class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        int arc_num = prerequisites.size();
        stack<int>stk;
        vector<int>in_degree(numCourses, 0);
        vector<vector<int>>G(numCourses, vector<int>{});
        vector<int>res;
        
        for(auto &arc : prerequisites){ // 建图
            in_degree[arc[0]]++;
            G[arc[1]].push_back(arc[0]);
        }
        
        for(int i = 0; i < numCourses; i++) // 先将所有入度为0的顶点入栈
            if(!in_degree[i]) stk.push(i);
        
        while(!stk.empty()){
            int course = stk.top(); stk.pop();
            res.push_back(course);
            for(int c: G[course]){ // 所有以course为起点的边的终点
                if(!(--in_degree[c])) stk.push(c);
            }
        }
        return res.size() == numCourses ? res : vector<int>{};
    }
};
```

## DFS
``` C++
class Solution {
private:
   bool DFS(vector<vector<int>>&G, vector<int>& visited, vector<int>& res, int i) {
       if (visited[i] == -1) return false;
       if (visited[i] == 1) return true;
       visited[i] = -1;
       for (auto a : G[i]) {
           if (!DFS(G, visited, res, a)) return false;
       }
       res.push_back(i);
       visited[i] = 1;
       return true;
   }
public:
   vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
       vector<vector<int>> G(numCourses, vector<int>());
       vector<int>visited(numCourses, 0);
       vector<int>res;
       
       for (auto &arc : prerequisites) {
           G[arc[1]].push_back(arc[0]);
       }
       
       for (int i = 0; i < numCourses; ++i)
           if (!DFS(G, visited, res, i)) return vector<int>{};
       
       // 注意最后要翻转一下
       reverse(res.begin(), res.end());
       return res;
   }
};
```
