Leetcode169: Course Schedule

来源:互联网 发布:单片机与嵌入式系统 编辑:程序博客网 时间:2024/05/21 23:34

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.

拓扑排序。用一个队列存入度为0的节点,依次出队,将与出队节点相连的节点的入度减1,如果入度减为0,将其放入队列中,直到队列为空。如里最后还有入度不为0的节点的话,说明有环,否则无环。

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<vector<int>> graph(numCourses, vector<int>(0));        vector<int> inDegree(numCourses, 0);        for(auto p : prerequisites)        {            graph[p.second].push_back(p.first);            ++inDegree[p.first];        }        queue<int> q;        for(int i = 0; i < numCourses; i++)        {            if(inDegree[i] == 0)                q.push(i);        }        while(!q.empty())        {            int tmp = q.front();            q.pop();            for(auto v : graph[tmp])            {                --inDegree[v];                if(inDegree[v] == 0)                    q.push(v);            }        }        for(int i = 0; i < numCourses; i++)        {            if(inDegree[i] != 0)    return false;        }        return true;    }};


0 0
原创粉丝点击