-
Notifications
You must be signed in to change notification settings - Fork 4
/
CourseSchedule
58 lines (58 loc) · 1.5 KB
/
CourseSchedule
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
void createGraph(vector<vector < int>> &pre, vector< vector< int>> &graph)
{
int e = pre.size();
for (int i = 0; i < e; i++)
{
graph[pre[i][1]].push_back(pre[i][0]);
}
}
bool finish(int n, vector<vector < int>> &prerequisites)
{
// topological sort
vector<int> indeg(n, 0);
vector<vector < int>> g(n, vector<int> (0));
createGraph(prerequisites, g);
int i;
for (i = 0; i < prerequisites.size(); i++)
{
indeg[prerequisites[i][0]]++;
}
bool chk = false;
queue<int> q;
int cnt = 0;
for (i = 0; i < n; i++)
{
if (indeg[i] == 0)
{
chk = 1;
q.push(i);
cnt++;
}
}
if (chk)
{
while (!q.empty())
{
int n1 = q.front();
q.pop();
for (int i = 0; i < g[n1].size(); i++)
{
indeg[g[n1][i]]--;
if (indeg[g[n1][i]] == 0)
{
q.push(g[n1][i]);
cnt++;
}
}
}
if (cnt == n)
{
return true;
}
}
return false;
}
bool canFinish(int n, vector<vector < int>> &prerequisites)
{
return finish(n,prerequisites);
}