leetcode練習 Course Schedul

最近一直是圖論的學習,還是找一個圖論的題目
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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章