liuyingbin19222 / leetcode_training

leetcode
0 stars 0 forks source link

图问题-207课程表 #2

Open liuyingbin19222 opened 4 years ago

liuyingbin19222 commented 4 years ago

输入: 2, [[1,0]] 输出: true 解释: 总共有 2 门课程。学习课程 1 之前,你需要完成课程 0。所以这是可能的。

liuyingbin19222 commented 4 years ago

课程表二解法: 使用拓扑排序输出顺序;

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> inDegree(numCourses,0); //   初始化将inDgree 矩阵每一个值为0;
        vector<vector<int>> adJust(numCourses,vector<int>()); //
        for(auto arr : prerequisites){
            inDegree[arr[0]]++;
            adJust[arr[1]].push_back( arr[0] );
        }
        queue<int> que;
        for(auto cnt = 0;cnt < inDegree.size();cnt++){
            if(inDegree[cnt] == 0) que.push( cnt );
        }
        vector<int> res;
        while(!que.empty()){
            auto tmp = que.front();
            que.pop();
            res.push_back(tmp);
            for(auto i : adJust[tmp]){
                if(--inDegree[i] == 0){
                    que.push(i);
                }
            }
        }
        if( res.size() == numCourses ) return res;
        else return {};
    }
};