240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 16 | Leetcode 207. Course Schedule

题解

Medium

方法:Topological Sort

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<vector<int>> graph(numCourses, vector<int>());
        vector<int> in(numCourses, 0);
        
        for(auto& pre : prerequisites) {
            graph[pre[1]].push_back(pre[0]);
            in[pre[0]]++;
        }
        
        queue<int> q;
        
        for(int i = 0; i < numCourses; i++) {
            if(in[i] == 0) q.push(i);
        }
        
        while(!q.empty()) {
            int t = q.front();
            q.pop();

            for(auto i : graph[t]) {
                in[i]--;
                if(in[i] == 0) q.push(i);
            }
        }
        
        for(auto x : in) {
            if(x != 0) return false;
        }
        
        return true;
    }
};
posted @ 2020-10-01 05:42  CasperWin  阅读(77)  评论(0编辑  收藏  举报