## Bernini @ buffalo

ME转CS,蛋疼菊紧中.........

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

#### 【LeetCode】Course Schedule II 解题报告

2015-05-19 17:13:08

#### Leetcode 210 Course Schedule II 课程表II

2015-08-14 16:29:04

#### LeetCode#210 Course Schedule II（C++版）

2017-09-24 23:28:03

#### [leetcode] 210. Course Schedule II 解题报告

2016-02-26 14:22:04

#### [leetcode-210]course scheduleII(java)

2015-07-16 21:45:04

#### 【LeetCode】Course Schedule 解题报告

2015-05-19 17:05:08

#### leetcode210——Course Schedule II

2018-03-21 14:59:38

#### Leetcode210-Course Schedule II

2015-05-15 00:30:24

#### 210. Course Schedule II（DFS）

2017-06-17 11:49:38