leetcode 207: Course Schedule

来源:互联网 发布:sql中in与all的区别 编辑:程序博客网 时间:2024/05/16 07:17

To solve the problem, we need to understand the problem in another way, which is whether there is a cycle in a directed graph. The algorithm we can use is Topological Sort.

First we need to set up an adjacency list to save the graph. Then use the queue and push into all vertices having 0 in-degree. While popping the vertices in the queue, reduce the in-degree of the vertices that are connected to, and push those having 0 in-degree into the queue. Finally, if all vertices have 0 in-degree, the graph does not contain a cycle.

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        unordered_map<int,vector<int> > pre;        vector<int> in_num(numCourses,0);        int n=prerequisites.size();        for(int i=0;i<n;i++)        {            pre[prerequisites[i].first].push_back(prerequisites[i].second);            in_num[prerequisites[i].second]++;        }                queue<int> q;        int count=0;        for(int i=0;i<numCourses;i++)            if(in_num[i]==0)            {                q.push(i);                count++;            }        while(!q.empty())        {            int curr_course=q.front();            q.pop();            for(int i=0;i<pre[curr_course].size();i++)            {                int temp_course=pre[curr_course][i];                in_num[temp_course]--;                if(in_num[temp_course]==0)                {                    q.push(temp_course);                    count++;                }            }        }        if(count!=numCourses)            return false;        return true;    }};


0 0
原创粉丝点击