lintcode616 - Course Schedule II - medium
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.
Input: n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
拓扑排序。统计每门课的入度,同时用一个map存key课可以使得{val1...valn}课能上了。宽搜队列里maintain入度为0的课,每次pop出来的push进拓扑序列。
最后check拓扑序列的长度是否等于全部课程的数量。
实现:
1 class Solution { 2 public: 3 /* 4 * @param numCourses: a total of n courses 5 * @param prerequisites: a list of prerequisite pairs 6 * @return: the course order 7 */ 8 vector<int> findOrder(int numCourses, vector<pair<int, int>> &prerequisites) { 9 // write your code here 10 11 unordered_map<int, vector<int>> edge; 12 vector<int> in_degree(numCourses, 0); 13 for (auto p: prerequisites){ 14 edge[p.second].push_back(p.first); 15 in_degree[p.first]++; 16 } 17 queue<int> q; 18 for (int i=0; i<numCourses; i++){ 19 if (in_degree[i] == 0) q.push(i); 20 } 21 22 vector<int> res; 23 while (!q.empty()){ 24 int cur = q.front(); 25 q.pop(); 26 res.push_back(cur); 27 for (int next : edge[cur]){ 28 in_degree[next]--; 29 if (in_degree[next] == 0) q.push(next); 30 } 31 } 32 33 if (res.size() == numCourses) return res; 34 else return {}; 35 } 36 };
错误点:c++里没有while(q)这种写法,要check container是否为empty。

浙公网安备 33010602011771号