LeetCode #210 - Course Schedule II - Medium

来源:互联网 发布:arp scan python 编辑:程序博客网 时间:2024/04/30 01:33

Course Schedule Series

Course Schedule I: http://blog.csdn.net/Arcome/article/details/53790947

Course Schedule II: http://blog.csdn.net/Arcome/article/details/53791005

Problem

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

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

Algorithm

整理一下题意:给定一组课程,课程之间有先修或后修的关系,要求判断能否修完给定的全部课程,若能修完全部课程,则返回课程修习的顺序;若不能修完,则返回空。
输入数据格式:给定整数numCourses和向量prerequisites:整数numCourses表示所有课程的数量;向量prerequisites包含一组pair格式的数据,如pair(a,b)表示修课程a前需要先修课程b。

本题与Course Schedule I的区别在于I只要判断能否修完,II在能修完的基础上要求输出修习课程的顺序。与I的代码几乎一样,只要将队列的元素用向量存起来,若判断不能修完,则将向量情况,若可以则不作修改,最后返回向量。

代码如下。

class Solution {public:    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<vector<int>> graph(numCourses,vector<int> (0));        vector<int> in(numCourses,0);        vector<int> path;        for(int i=0;i<prerequisites.size();i++){            graph[prerequisites[i].second].push_back(prerequisites[i].first);            in[prerequisites[i].first]++;        }        queue<int> q;        for(int i=0;i<numCourses;i++){            if(in[i]==0) q.push(i);        }        while(!q.empty()){            int p=q.front();            q.pop();            path.push_back(p);            for(int i=0;i<graph[p].size();i++){                in[graph[p][i]]--;                if(in[graph[p][i]]==0) q.push(graph[p][i]);            }        }        for(int i=0;i<numCourses;i++){            if(in[i]!=0) path.clear();        }        return path;    }};
0 0
原创粉丝点击