Leetcode 210. Course Schedule II

Lintcode 616. Course Schedule II

Posted by Olivia Liu on August 15, 2019 | 阅读:

Description

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Answer

The main idea is identical with Course Schedule. To return the ordering, push the top element in queue for each time. The top element of queue each time is the next course needs to be taken.

Code

C++

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        if(numCourses == 0) return {};
        int n = prerequisites.size();
        vector<int> res;
        vector<int> indegree(numCourses, 0);
        vector<unordered_multiset<int>> edges(numCourses);
        for(int i = 0; i < n; ++i)
        {
            edges[prerequisites[i][1]].insert(prerequisites[i][0]);
            indegree[prerequisites[i][0]]++;
        }
        queue<int> q;
        for(int i = 0; i < numCourses; ++i)
            if(indegree[i] == 0) q.push(i);
        while(!q.empty())
        {
            int cur = q.front();
            q.pop();
            res.push_back(cur);
            for(auto it = edges[cur].begin(); it != edges[cur].end(); ++it)
            {
                indegree[*it]--;
                if(indegree[*it] == 0) q.push(*it);
            }
        }
        return res.size() == numCourses ? res : vector<int>();
    }
};