-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomeWork03_Course_ScheduleII.cpp
More file actions
61 lines (44 loc) · 1.41 KB
/
HomeWork03_Course_ScheduleII.cpp
File metadata and controls
61 lines (44 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> result;
graph = vector<vector<int>>(numCourses,vector<int>());
in_degree = vector<int>(numCourses);
//build a graph
for(auto prerequisite : prerequisites){
Add_Edge(prerequisite[1],prerequisite[0]);
}
top_sort(result);
if(result.size() < numCourses) return { };
return result;
}
private:
vector<vector<int>> graph;
vector<int> in_degree;
//x -> y
void Add_Edge(int x, int y){
graph[x].push_back(y);
in_degree[y]++;
}
void top_sort(vector<int>& result){
queue<int> No_need_pre;
for(int i =0; i < in_degree.size(); i++){
if(in_degree[i] == 0){
No_need_pre.push(i);
}
}
while(!No_need_pre.empty()){
//取出对头
int node = No_need_pre.front();
result.push_back(node);
No_need_pre.pop();
//加入新的可修
for(int a : graph[node]){
in_degree[a]--;
if(in_degree[a] == 0){
No_need_pre.push(a);
}
}
}
}
};