Leetcode 207. Course Schedule

bool canFinish(int numCourses, vector>& prerequisites) {
    vector> matrix(numCourses,vector(numCourses,0));
    vector inDegree(numCourses);
    
    for(int i = 0;i < prerequisites.size();i++){
        int pre =  prerequisites[i].second;
        int ready = prerequisites[i].first;
        if(matrix[pre][ready] == 0){
            inDegree[ready]++;
            matrix[pre][ready] ++;
        }
    }
    
    int count = 0;
    queue queue;
    for(int i = 0;i < inDegree.size();i++){
        if(inDegree[i] == 0){
            queue.push(i);
        }
    }
    
    while(!queue.empty()){
        int course = queue.front();
        queue.pop();
        count ++;
        for(int i = 0;i < numCourses;i++){
            if(matrix[course][i] != 0){
                if(--inDegree[i] == 0){
                    queue.push(i);
                }
            }
        }
    }
    return count == numCourses;
    
}

你可能感兴趣的:(Leetcode 207. Course Schedule)