LeetCode 207. Course Schedule

Posted 約束の空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 207. Course Schedule相关的知识,希望对你有一定的参考价值。

拓扑排序的题目,如果b的前置课程是a,则 a->b。首先计算每个节点的入度,入度为0的结点放到队列中,类似BFS。如果最后有结点的度不为0,说明不行(有环存在)。

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
        vector<int> indegree=count_indegree(graph);
        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 (int nextnode:graph[tmp]){
                --indegree[nextnode];
                if (indegree[nextnode]==0)
                    q.push(nextnode);
            }
        }
        for (int i=0;i<numCourses;++i){
            if (indegree[i]!=0) return false;
        }
        return true;
    }
private:
    vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites){
        vector<unordered_set<int>> graph(numCourses);
        for (auto pre:prerequisites){
            graph[pre.second].insert(pre.first);
        }
        return graph;
    }
    
    vector<int> count_indegree(vector<unordered_set<int>> graph){
        vector<int> indegree(graph.size(),0);
        for (auto nextnodes:graph){
            for (int nextnode:nextnodes){
                ++indegree[nextnode];
            }
        }
        return indegree;
    }
};

 

以上是关于LeetCode 207. Course Schedule的主要内容,如果未能解决你的问题,请参考以下文章

leetcode207 Course Schedule

leetcode [207]Course Schedule

leetcode 207. Course Schedule

LeetCode 207. Course Schedule(拓扑排序)

[LeetCode] 207. Course Schedule 课程安排

leetcode 207. Course Schedule 课程计划 ---------- java