Course Schedule II

来源:互联网 发布:淘宝的收费方式 编辑:程序博客网 时间:2024/06/06 11:53

There are a total of n courses you have to take, labeled from 0 ton - 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.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is[0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is[0,1,2,3]. Another correct ordering is[0,2,1,3].

Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices

class Solution {public:    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<set<int> > graph = make_graph(numCourses, prerequisites);        vector<int> degrees = compute_indegree(graph);        queue<int> zeros;        for (int i = 0; i < degrees.size(); i++)        {            if (degrees[i] == 0)            {                zeros.push(i);            }        }        vector<int> result;        while (!zeros.empty())        {            int zero = zeros.front();            zeros.pop();            result.push_back(zero);            for (set<int>::iterator it = graph[zero].begin(); it != graph[zero].end(); it++)            {                degrees[*it]--;                if (degrees[*it] == 0)                {                    zeros.push(*it);                }            }            numCourses--;        }        if (numCourses)        {            result.clear();        }            return result;    }private:    vector<set<int> > make_graph(int numCourses, vector<pair<int, int> > &prerequisites)    {        vector<set<int> > graph(numCourses);        for (vector<pair<int, int> >::iterator it = prerequisites.begin(); it != prerequisites.end(); it++)        {            graph[it->second].insert(it->first);        }        return graph;    }    vector<int> compute_indegree(vector<set<int> > &graph)    {        vector<int> degrees(graph.size(), 0);        for (int i = 0; i < graph.size(); i++)        {            for (set<int>::iterator it = graph[i].begin(); it != graph[i].end(); it++)            {                degrees[*it]++;            }        }        return degrees;    }};


0 0