【LeetCode】210. Course Schedule II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/KID_LWC/article/details/82534585

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

题解:跟之前判断环的题一样,只是加了完成课程的学习路径,这条路径刚好对应每个从递归栈弹出的点,所以在弹出后加入一个vector即可,这里犯错有两个刚开始res忘记加上&,后来color忘记加上&

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
        const int MAXN = 2010;
        vector<int> G[numCourses];
        vector<int> color(numCourses,0);
        for(int i=0;i<prerequisites.size();i++){
            G[prerequisites[i].first].push_back(prerequisites[i]. second);
            
        }
        vector<int> res;
        vector<int> ans;
        for(int i=0;i<numCourses;i++){
            if(!dfs(G,i,color,res)) return ans;
        }
        return res;
    }
                                                                                                                                               
    bool dfs(vector<int> G[],int u,vector<int>& color,vector<int>& res){
        if(color[u]!=0)return color[u]==2;
        color[u]=1;
        for(auto x:G[u]){
            if(color[x]==1||!dfs(G,x,color,res)){
                return false;
            }
        }
        
        color[u]=2;
        res.push_back(u);
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/KID_LWC/article/details/82534585