[LeetCode]Course Schedule II

来源:互联网 发布:数据挖掘技术与算法 编辑:程序博客网 时间:2024/06/18 18:10

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.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

DFS , 参考Course Schedule ,保留调用的Order。注意题目中的顺序

class Solution {public:    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<vector<int>> V(numCourses);        vector<int> Order;        for(int i=0; i<prerequisites.size(); ++i){            V[prerequisites[i].first].push_back(prerequisites[i].second);        }        vector<bool> marked(numCourses,false);        vector<bool> onstack(numCourses,false);        bool cycle = false;        for(int i=0; i<numCourses; ++i){            if(!marked[i])                dfs(V,i,marked,onstack,cycle,Order);//DFS        }        if(cycle == true)            return vector<int>(0);        else{            return Order;        }        return Order;    }    void dfs(vector<vector<int>> &V,int Vindex,vector<bool> &marked,vector<bool> &onstack,bool &cycle,vector<int> &Order){        onstack[Vindex] = true;//stack        marked[Vindex] = true;//marked         for(int i=0; i<V[Vindex].size(); ++i){            if(cycle == true)                return;            int w = V[Vindex][i];            if(!marked[w]){                dfs(V,w,marked,onstack,cycle,Order);            }            else if(onstack[w])                cycle = true;        }        Order.push_back(Vindex);        onstack[Vindex] = false;    }};

 

0 0
原创粉丝点击