Course Schedule II

Question:

http://www.lintcode.com/en/problem/course-schedule-ii/
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.

Example

Given n = 2, prerequisites = [[1,0]]
Return [0,1]
Given n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Return [0,1,2,3] or [0,2,1,3]

Answer:

class Solution {
public:
    /*
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: the course order
     */
    vector<int> findOrder(int numCourses, vector<pair<int, int>> &prerequisites) {
        // write your code here
        vector<vector<int>> adj(numCourses);
        vector<int> indegree(numCourses);
        for (int i = 0; i < numCourses; i++)
             indegree[i] = 0;
        for (auto pq : prerequisites) {
            adj[pq.second].push_back(pq.first);
            indegree[pq.first]++;
        }
        stack<int> st;
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0)
                st.push(i);
        }
        int count = 0;
        vector<int> result;
        while (!st.empty()) {
            int v1 = st.top();
            st.pop();
            count++;
            result.push_back(v1);
            for (auto v2 : adj[v1]) {
                indegree[v2]--;
                if (indegree[v2] == 0)
                    st.push(v2);
            }
        }
        if (count != numCourses) {
            return vector<int>();
        }
        return result;
    }
};

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)