210. 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 1:

Input: 2, [[1,0]] 
Output: [0,1]
Explanation: 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] .
-------------------------------------------------------------------------
Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: 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] .

 

有n门课程,标号0~n-1,修某些课程之前,需要先修另外一些课程,用prerequisites表示。

输出修课顺序,如果不能修完,输出空。

 

典型的拓扑排序。

 1 class Solution {
 2     vector<vector<int>> graph;
 3     vector<int> in_degree;
 4     queue<int> q;
 5     vector<int> ans;
 6 public:
 7     void BuildGraph(int numCourses, vector<pair<int, int>>& prerequisites) {
 8         graph = vector<vector<int>>(numCourses);
 9         in_degree = vector<int>(numCourses);
10         for (auto &p: prerequisites) {
11             int e = p.first;
12             int s = p.second;
13             graph[s].push_back(e);
14             ++in_degree[e];
15         }
16     }
17     
18     void TopoSort(int numCourses) {
19         for (int i = 0; i < numCourses; ++i) {
20             if (in_degree[i] == 0)
21                 q.push(i);
22         }
23         
24         while (!q.empty()) {
25             int idx = q.front();
26             q.pop();
27             ans.push_back(idx);
28             
29             for (auto &p: graph[idx]) {
30                 if (--in_degree[p] == 0)
31                     q.push(p);
32             }
33         }
34     }
35     vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
36         BuildGraph(numCourses, prerequisites);
37         TopoSort(numCourses);
38         if (ans.size() == numCourses)
39             return ans;
40         return {};
41     }
42 };

 

posted @ 2018-07-24 16:03  Zzz...y  阅读(799)  评论(0编辑  收藏  举报