跳转至

课程表⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<vector<int>> edges(numCourses);
        vector<int> inDegrees(numCourses);

        for (const auto& info : prerequisites) {
            edges[info[1]].push_back(info[0]);
            inDegrees[info[0]]++;
        }

        queue<int> q;
        for (int i = 0; i < numCourses; i++) {
            if (inDegrees[i] == 0)
                q.push(i);
        }

        int count = 0;
        while (!q.empty()) {
            int current = q.front();
            q.pop();
            count++;
            for (int v : edges[current]) {
                if (--inDegrees[v] == 0)
                    q.push(v);
            }
        }

        return count == numCourses;
    }
};