Leetcode -- Course Schedule

来源:互联网 发布:ant 调用python 编辑:程序博客网 时间:2024/05/29 16:16

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.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

分析:

拓扑排序。

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<int> in(numCourses,0);        vector<pair<int, int>>::iterator it;        vector<int> out;        queue<int> zeroin;        int n=prerequisites.size();        for(int i=0;i<n;++i)            in[prerequisites[i].second]++;        for(int i=0;i<numCourses;++i)            if(in[i]==0)                zeroin.push(i);        while(!zeroin.empty())        {            int cur = zeroin.front();            zeroin.pop();            out.push_back(cur);            for(it=prerequisites.begin();it!=prerequisites.end();)            {                if(it->first==cur)                {                    in[it->second]--;                    if(in[it->second]==0) zeroin.push(it->second);                    prerequisites.erase(it);                }                else                it++;            }        }        return out.size()==numCourses;    }};


0 0
原创粉丝点击