forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0207.cpp
38 lines (37 loc) · 836 Bytes
/
0207.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
class Solution
{
public:
bool canFinish(int n, vector<vector<int>>& pre)
{
vector<vector<int>> g(n, vector<int>());
vector<int> d(n, 0);
vector<int> vis(n, 0);
for (auto& p : pre)
{
g[p[1]].push_back(p[0]);
d[p[0]]++;
}
queue<int> q;
for (int i = 0; i < n; i++)
{
if (d[i] == 0)
{
q.push(i);
vis[i] = 1;
}
}
while (!q.empty())
{
int cur = q.front(); q.pop(); n--;
for (auto i : g[cur])
{
if (!vis[i] and --d[i] == 0)
{
vis[i] = 1;
q.push(i);
}
}
}
return n == 0;
}
};