leetcode210. 课程表 II

拓扑排序

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        int degree[numCourses];
        int M=numCourses*numCourses;
        int h[numCourses],ne[M],e[M],idx=0;
        memset(degree,0,sizeof degree);
        memset(h,-1,sizeof h);
        for(auto t:prerequisites){
            int a=t[1],b=t[0];
            e[idx]=b;
            ne[idx]=h[a];
            h[a]=idx++;
            ++degree[b];
        }
        vector<int> ans;
        int hh=0,tt=-1,q[M];
        for(int i=0;i<numCourses;i++){
            if(!degree[i]){
                q[++tt]=i;
            }
        }
        while(hh<=tt){
            int t=q[hh++];
            ans.push_back(t);
            for(int i=h[t];i!=-1;i=ne[i]){
                int j=e[i];
                if(--degree[j]==0)q[++tt]=j;
            }
        }
        if(tt<numCourses-1)return {};
        return ans;
    }
};