-
Notifications
You must be signed in to change notification settings - Fork 481
/
0210.cpp
40 lines (39 loc) · 923 Bytes
/
0210.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
class Solution
{
public:
vector<int> findOrder(int n, vector<vector<int>>& prerequisites)
{
unordered_map<int, vector<int>> g;
vector<int> d(n), vis(n), res;
for (auto& it : prerequisites)
{
g[it[1]].push_back(it[0]);
d[it[0]]++;
}
queue<int> q;
for (int i = 0; i < n; i++)
{
if (d[i] == 0)
{
q.push(i);
vis[i] = 1;
}
}
while (!q.empty())
{
auto cur = q.front(); q.pop();
res.push_back(cur);
n--;
for (int i : g[cur])
{
d[i]--;
if (!vis[i] and d[i] == 0)
{
vis[i] = 1;
q.push(i);
}
}
}
return n == 0 ? res : vector<int>();
}
};