Course Schedule II

题目:

here 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.

分析:

跟上一道题目一样,只是这次需要记录一个topo sort的order,同时在结尾判断是不是valid。

解法:

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int> > neighbors(numCourses, vector<int>() );
        vector<int> degree(numCourses, 0);
        for (int i = 0; i < prerequisites.size(); i++) {
            int first = prerequisites[i].first;
            int second = prerequisites[i].second;
            neighbors[second].push_back(first);
            degree[first] += 1;
        }

        queue<int> Q;
        for (int i = 0; i < numCourses; i++) {
            if (degree[i] == 0) {
                Q.push(i);
            }
        }

        vector<int> res;
        while (!Q.empty() ) {
            int temp = Q.front();
            Q.pop();
            degree[temp] -= 1;
            res.push_back(temp);
            for(int i = 0; i < neighbors[temp].size(); i++) {
                degree[neighbors[temp][i] ] -= 1;
                if (degree[neighbors[temp][i] ] == 0) {
                    Q.push(neighbors[temp][i]);
                }
            }
        }

        if (res.size() == numCourses) {
            return res;
        } else {
            return vector<int>();
        }
    }
};

results matching ""

    No results matching ""