【leedcode】210. Course Schedule II

来源:互联网 发布:淘宝产品视频拍摄 编辑:程序博客网 时间:2024/05/16 08:12

题目:

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 <iostream>
#include <vector>
#include <list>
#include <queue>
using namespace std;
struct  Node
{
int name;
int du;
Node(int name_, int du_) {
name = name_;
du = du_;
}
Node() {
name = 0;
du = 0;
}
};
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<list<Node> > graph;
vector<int> re;
for (int i = 0; i < numCourses; i++) {
// cout << "in1 " << endl;
list<Node> temp;
Node a(i,0);
temp.push_back(a);
graph.push_back(temp);
}
for (int i = 0; i < prerequisites.size(); i++) {
// cout << "in2 " << endl;
Node a(prerequisites[i].first, 0);
graph[prerequisites[i].second].push_back(a);
graph[prerequisites[i].first].front().du++;
}
queue<Node> que;
for (int i = 0; i < graph.size(); i++) {
if (graph[i].front().du == 0) {
que.push(graph[i].front());
re.push_back(graph[i].front().name);
}
}
int count = 0;
while (!que.empty()) {
// cout << "in";
Node t = que.front();
que.pop();
count++;
list<Node> ::iterator it = graph[t.name].begin();
for (it; it != graph[t.name].end(); it++) {
graph[it->name].front().du--;
if (graph[it->name].front().du == 0) {
que.push(graph[it->name].front());
re.push_back(it->name);
}
}
}
if (que.empty()) {
if (count == graph.size()) {
return re;
}
else {
vector <int> false1;
return false1;
}
}

}


};

0 0
原创粉丝点击