1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { vector<vector<int>> edges(numCourses, vector<int>()); vector<int> indeg(numCourses, 0); for (const auto& info : prerequisites) { edges[info[1]].push_back(info[0]); ++indeg[info[0]]; } queue<int> q; for (int i = 0; i < numCourses; ++i) if (indeg[i] == 0) q.push(i); while (!q.empty()) { --numCourses; int u = q.front(); q.pop(); for (int v : edges[u]) if (--indeg[v] == 0) q.push(v); } return numCourses == 0; } };
|