-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse_Schedule_II.cpp
More file actions
54 lines (53 loc) · 1.29 KB
/
Course_Schedule_II.cpp
File metadata and controls
54 lines (53 loc) · 1.29 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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> in_degree(numCourses, 0); //存储入度
vector<unordered_set<int>> matrix(numCourses);//存储图
vector<int> res;
for (int i = 0; i < prerequisites.size(); i++)
{
matrix[prerequisites[i].second].insert(prerequisites[i].first);
}
//计算入度
for (int i = 0; i < numCourses; i++)
{
for (auto it = matrix[i].begin(); it != matrix[i].end(); it++)
{
in_degree[*it]++;
}
}
stack<int> zeor_degree_stack;//存储入度为0的节点
int count = 0;//入度0的节点计数器
for (int i = 0; i < numCourses; i++)
{
if (in_degree[i] == 0)
{
zeor_degree_stack.push(i);
count++; //入度为0,计数加1
res.push_back(i);
}
}
//循环抽取入度为0的节点
while (!zeor_degree_stack.empty())
{
int top = zeor_degree_stack.top();
zeor_degree_stack.pop();
for (auto it = matrix[top].begin(); it != matrix[top].end(); it++)
{
in_degree[*it]--;
if (in_degree[*it] == 0)
{
zeor_degree_stack.push(*it);
count++;
res.push_back(*it);
}
}
}
if (count == numCourses)
return res;
else
{
vector<int> tmp; return tmp;
}
}
};