leetcode练习 Course Schedul

来源:互联网 发布:怎么用python画图 编辑:程序博客网 时间:2024/06/06 08:24

最近一直是图论的学习,还是找一个图论的题目
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.
You may assume that there are no duplicate edges in the input prerequisites.

一个很经典的拓扑排序,多余的话也就不说了,直接上代码

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<vector<int>> pre(numCourses);        int N = prerequisites.size();        vector<int> inDegree(numCourses,0);        for (int i=0;i<N;++i){            auto p = prerequisites[i];            inDegree[p.first]++;            pre[p.second].push_back(p.first);        }        queue<int> que;        for (int i=0;i<numCourses;++i){            if (inDegree[i]==0) que.push(i);        }        int count=0;        while(!que.empty()){            int acc=que.front();            que.pop();            ++count;            for (auto st:pre[acc]){                if (inDegree[st]==1){                    que.push(st);                }                inDegree[st]--;            }        }        return count==numCourses;    }};
原创粉丝点击