landscapemi的博客

###### leetcode_c++:图：Course Schedule II (207)

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.

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

#include <bits/stdc++.h>

using namespace std;
const int N = 0;

class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
graph = vector<vector<int> >(numCourses);
vis = vector<int>(numCourses);

vector<int> inorder(numCourses);
vector<int> path;
// generate the tree map
for (auto prerequisite : prerequisites) {
graph[prerequisite.second].push_back(prerequisite.first);
inorder[prerequisite.first] += 1;
}
// find out 0-in-order node and dfs
for (int i = 0; i < numCourses; ++i) {
if (inorder[i] == 0) {
if (dfs(i, path) == false) // can not topsort
return vector<int>();
}
}
if (path.size() != numCourses)
return vector<int>();
reverse(path.begin(), path.end());
return path;
}
private:
vector<vector<int> > graph;
vector<int> vis;

bool dfs(int id, vector<int> &path) {
vis[id] = 1; // visiting
for (auto toid : graph[id]) {
if (vis[toid] == 1)
return false;
if (vis[toid] == 2)
continue;
if (dfs(toid, path) == false)
return false;
}
vis[id] = 2; // visited
path.push_back(id);
return true;
}
};

int main() {
Solution s;
vector<pair<int, int>> prerequisites;
prerequisites.push_back(pair<int, int>(0, 2));
prerequisites.push_back(pair<int, int>(2, 0));
prerequisites.push_back(pair<int, int>(1, 2));
vector<int> res = s.findOrder(3, prerequisites);
for (auto x : res) cout << x << ' ';
return 0;
}

#### leetcode_c++:图：Course Schedule(207)

2016-08-28 15:08:20

#### 【LeetCode】207. Course Schedule

2016-05-30 23:40:09

#### leetcode 207: Course Schedule

2015-05-20 05:07:51

#### Leetcode解题报告：207. Course Schedule

2016-11-26 23:47:38

#### [LeetCode]207. Course Schedule 课程表

2018-03-03 21:52:47

#### [leetcode] 207. Course Schedule 解题报告

2016-02-26 14:10:16

#### LeetCode 207、Course Schedule 题解

2017-03-12 12:29:16

#### leetcode Course Schedule

2015-08-04 11:40:57

#### 207. Course Schedule

2016-07-30 23:33:54

#### LeetCode 207 - Course Schedule

2015-05-07 02:24:40

## 不良信息举报

leetcode_c++:图：Course Schedule II (207)