拓扑排序:课程表Course Schedule2

https://leetcode.com/problems/course-schedule-ii/

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {

        vector<int> res;
        vector<int> inDgree(numCourses,0);
        map<int, vector<int> >adjNode;

        int len = prerequisites.size();
        for (int i = 0; i < len; i++){
            pair<int, int> p = prerequisites[i];

            //自环
            if (p.first == p.second)
                return res;

            //平行边
            if (find(adjNode[p.second].begin(), adjNode[p.second].end(), p.first) == adjNode[p.second].end()){
                adjNode[p.second].push_back(p.first);
                inDgree[p.first]++;
            }
        }

        queue<int> Q;

        for (int i=0; i < numCourses; i++){
            if (inDgree[i] == 0)
                Q.push(i);
        }

        while (!Q.empty()){
            int front = Q.front();
            Q.pop();

            res.push_back(front);

            vector<int> adj = adjNode[front];

            for (int i:adj){
                inDgree[i]--;
                if (inDgree[i] == 0){
                    Q.push(i);
                }
            }
        }

        if (res.size() == numCourses){
            return res;
        }
        else{
            return vector<int>();
        }

    }


};
    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/gao1440156051/article/details/51547081
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞