-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path210. Course Schedule II.cpp
49 lines (33 loc) · 999 Bytes
/
210. 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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> count (numCourses, 0);
map<int,vector<int> > nodes;
vector<int> result;
for(auto it:prerequisites) {
nodes[it.second].push_back(it.first);
count[it.first]++;
}
queue<int> q;
for(int i = 0; i< count.size(); ++i){
if (count[i] == 0)
q.push(i);
}
while(!q.empty()) {
int top = q.front();
q.pop();
result.push_back(top);
for(auto it = nodes[top].begin(); it!=nodes[top].end(); ++it) {
count[*it]--;
if (!count[*it])
q.push(*it);
}
if(nodes.find(top)!=nodes.end())
nodes.erase(top);
}
if (nodes.empty())
return result;
else
return vector<int> ();
}
};