# 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 II (207) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)