forked from MountAim/Graph-Coding-Minutes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
20-Course Schedule II.cpp
51 lines (50 loc) · 1.02 KB
/
20-Course Schedule II.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
#include<bits/stdc++.h>
using namespace std;
vector<int> findOrder(int numCourses, vector<vector<int>> prerequisites) {
vector<vector<int>>v(numCourses+1);
int x,y,val;
vector<int>ind(numCourses+1);
for(int i=0;i<prerequisites.size();i++)
{
x=prerequisites[i][0],y=prerequisites[i][1];
v[y].push_back(x);
ind[x]++;
}
queue<int>q;
vector<int>topo;
set<int>s;
for(int i=0;i<numCourses;i++)
{
if(ind[i]==0)
{
s.insert(i);
}
}
for(auto itr:s)
{
q.push(itr);
}
while(q.size())
{
x=q.front();
q.pop();
topo.push_back(x);
s.clear();
for(auto itr:v[x])
{
ind[itr]--;
if(ind[itr]==0){
s.insert(itr);
}
}
for(auto itr:s)
{
q.push(itr);
}
}
if(topo.size()!=numCourses)
{
return {};
}
return topo;
}