|
| 1 | +## Course Schedule II |
| 2 | + |
| 3 | +There are a total of n courses you have to take, labeled from 0 to n - 1. |
| 4 | + |
| 5 | +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] |
| 6 | + |
| 7 | +Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. |
| 8 | + |
| 9 | +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. |
| 10 | + |
| 11 | +For example: |
| 12 | + |
| 13 | +``` |
| 14 | +2, [[1,0]] |
| 15 | +``` |
| 16 | + |
| 17 | +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]` |
| 18 | + |
| 19 | +``` |
| 20 | +4, [[1,0],[2,0],[3,1],[3,2]] |
| 21 | +``` |
| 22 | + |
| 23 | +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]`. |
| 24 | + |
| 25 | +Note: |
| 26 | +*The input prerequisites is a graph represented by a list of edges, not adjacency matrices.* |
| 27 | + |
| 28 | +Hints: |
| 29 | + |
| 30 | +* This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. |
| 31 | +* Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. |
| 32 | +* Topological sort could also be done via BFS. |
| 33 | + |
| 34 | +## Solution |
| 35 | + |
| 36 | +求拓扑排序结果, 算法见[Course Schedule](../Course Schedule) |
| 37 | + |
| 38 | +```cpp |
| 39 | +vector<int> topsort(int n, const vector<pair<int, int>> &request) { |
| 40 | + vector<int> result; |
| 41 | + vector<int> degree(n, 0); |
| 42 | + for (auto p : request) { |
| 43 | + degree[p.first]++; |
| 44 | + } |
| 45 | + while (result.size() < n) { // 还没有访问完 |
| 46 | + int cur = findZero(degree); |
| 47 | + if (cur >= 0) { // 访问节点cur |
| 48 | + result.push_back(cur); |
| 49 | + degree[cur] = -1; // 标记当前节点为已经访问状态 |
| 50 | + for (auto p : request) { |
| 51 | + if (p.second == cur) |
| 52 | + degree[p.first]--; // 去掉已访问节点 |
| 53 | + } |
| 54 | + } else |
| 55 | + return vector<int>(); |
| 56 | + } |
| 57 | + return result; |
| 58 | +} |
| 59 | +``` |
0 commit comments