【leecode】 Course Schedule

class Solution {
public:
    static bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        //初始化入度
        vector<int> indegree(numCourses, 0);
        //初始化邻接表
        vector<vector<int>> g(numCourses,  vector<int>(0));
        for (int i = 0; i < prerequisites.size(); i++) {
            int first = prerequisites.at(i).first;
            int second = prerequisites.at(i).second;
            g[second].push_back(first);
            indegree[first] ++;
        }
        queue<int> que;
        for (int i = 0; i < numCourses; i++) {
            if (indegree.at(i) == 0) {
                que.push(i);
            }
        }
        while(!que.empty()) {
            int u = que.front();
            que.pop();
            for (auto v : g[u]) {
                indegree[v] --;
                if (indegree.at(v) == 0) {
                    que.push(v);
                }
            }
        }

        for (auto v : indegree) {
            if (v != 0) {
                return false;
            }
        }
        return true;
    }
};
View Code

 

posted @ 2017-04-20 21:13  南岛的森林  阅读(122)  评论(0编辑  收藏  举报