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
| class Solution { public: bool canFinish(int n, vector<vector<int>>& edges) { vector<vector<int>> g(n); vector<int> d(n); for(auto& e: edges) { int a = e[0], b = e[1]; g[a].push_back(b); d[b]++; }
queue<int> q; for(int i=0;i<n;i++) { if(d[i] == 0) { q.push(i); } } int cnt = 0; while(q.size()) { auto t = q.front(); q.pop(); cnt++; for(auto i: g[t]) { if(--d[i] == 0) { q.push(i); } } } return cnt == n; } };
|