[LeetCode]Course Schedule

来源:互联网 发布:吉他谱制谱软件 编辑:程序博客网 时间:2024/06/18 10:55

Course Schedule

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, is it possible for you to finish all courses?

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 it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

DFS搜索,系统维护的递归调用栈就是当前正在遍历的有向路径。一旦我们找到了一条有向边,v->w且w已经存在于栈中,就找到了一个环。
用一个onstack数组保存,递归调用栈的过程,判断是否有环。
class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<vector<int>> V(numCourses);        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);//DFS        }        return !cycle;    }    void dfs(vector<vector<int>> &V,int Vindex,vector<bool> &marked,vector<bool> &onstack,bool &cycle){        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);            }            else if(onstack[w])                cycle = true;        }        onstack[Vindex] = false;    }};</span>



0 0