Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
- unordered_map<int, int> degree;
- unordered_map<int, unordered_set<int>> graph;
- for (int i = 0; i < numCourses; ++i) {
- degree[i] = 0;
- }
- for (const auto& course: prerequisites) {
- degree[course[0]]++;
- graph[course[1]].insert(course[0]);
- }
- queue<int> q;
- for (int i = 0; i < numCourses; ++i) {
- if (degree[i] == 0) {
- q.push(i);
- }
- }
- while (!q.empty()) {
- int id = q.front(); q.pop();
- numCourses--;
- for (const auto& child : graph[id]) {
- degree[child]--;
- if (degree[child] == 0) {
- q.push(child);
- }
- }
- }
- return numCourses == 0;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement