-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse Schedule.cpp
85 lines (72 loc) · 1.69 KB
/
Course Schedule.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class Solution
{
public:
class graph
{
int vertex;
list<int> *l;
public:
graph(int v)
{
this->vertex = v;
l = new list<int>[vertex];
}
void edge(int i, int j, bool directed = false)
{
l[i].push_back(j);
if (directed)
{
l[j].push_back(i);
}
}
vector<int> topologicalsort()
{
vector<int> degree(vertex, 0);
for (int i = 0; i < vertex; i++)
{
for (auto nbr : l[i])
{
degree[nbr]++;
}
}
queue<int> q;
for (int i = 0; i < vertex; i++)
{
if (degree[i] == 0)
{
q.push(i);
}
}
vector<int> res;
while (!q.empty())
{
int front = q.front();
res.push_back(front);
q.pop();
for (auto nbr : l[front])
{
degree[nbr]--;
if (degree[nbr] == 0)
{
q.push(nbr);
}
}
}
return res;
}
};
vector<int> findOrder(int n, int m, vector<vector<int>> prerequisites)
{
graph g(n);
for (auto preq : prerequisites)
{
g.edge(preq[1], preq[0]);
}
vector<int> result = g.topologicalsort();
if (result.size() != n)
{
return vector<int>();
}
return result;
}
};