# leecode_210 Course Schedule II

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

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

vector<vector<int>> pre_course;
vector<vector<int>> next_course;
vector<int>temp;
unordered_set<int> set;
queue<int>  que;
vector<int> res;

for (int i=0;i<numCourses;i++){
//next_temp.push_back(temp);
pre_course.push_back(temp);
next_course.push_back(temp);
}

for (int i=0;i<prerequisites.size();i++){
int from=prerequisites[i].second;
int to=prerequisites[i].first;
pre_course[to].push_back(from);
next_course[from].push_back(to);
}

for (int i=0;i<numCourses;i++){
if (pre_course[i].size()==0)
que.push(i);

}

while(!que.empty()){
int course_taking=que.front();
que.pop();

if (set.find(course_taking)==set.end()) {
set.insert(course_taking);
res.push_back(course_taking);
bool all_pre_ok=true;

for (int i=0;i<next_course[course_taking].size();i++){
int next_cour=next_course[course_taking][i];
for (int j=0;j<pre_course[next_cour ].size();j++){
if (set.find( pre_course[ next_cour ][j] ) == set.end())
all_pre_ok=false;

}

if (all_pre_ok)
que.push(next_course[course_taking][i]);

all_pre_ok=true;
}

}
}

if (res.size()<numCourses)
res.clear();
return res;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：leecode_210 Course Schedule II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)