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

95人阅读 评论(0)

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;
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：102271次
• 积分：6682
• 等级：
• 排名：第3496名
• 原创：589篇
• 转载：2篇
• 译文：0篇
• 评论：2条
评论排行
最新评论