https://leetcode.com/problems/course-schedule-ii/description/?envType=study-plan-v2&envId=top-interview-150

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        vector<vector<int>> edges(numCourses);
        vector<int> inDegree(numCourses, 0);
        for (auto &x: prerequisites) {
            inDegree[x[0]] += 1;
            edges[x[1]].push_back(x[0]);
        }
        vector<int> res;
        queue<int> q;
        for (int i = 0; i < numCourses; i++)
            if (inDegree[i] == 0) q.push(i);
        while (!q.empty()) {
            int cur = q.front();
            q.pop();
            res.push_back(cur);
            for (auto &x: edges[cur]) {
                inDegree[x] -= 1;
                if (inDegree[x] == 0) q.push(x);
            }
        }
        if (res.size() != numCourses) return {};
        return res;
    }
};

Time Complexity: O(n)
Space: O(n)

經典的拓樸排序算法