# leecode_210 Course Schedule II

130人阅读 评论(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].

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：23011次
• 积分：1706
• 等级：
• 排名：千里之外
• 原创：152篇
• 转载：9篇
• 译文：0篇
• 评论：13条
阅读排行
最新评论