C++ | Leetcode C++题解之第207题课程表

题目:

题解:

cpp 复制代码
class Solution {
private:
    vector<vector<int>> edges;
    vector<int> indeg;

public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        edges.resize(numCourses);
        indeg.resize(numCourses);
        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);
            }
        }

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

        return visited == numCourses;
    }
};
相关推荐
big_rabbit050242 分钟前
[算法][力扣222]完全二叉树的节点个数
数据结构·算法·leetcode
张李浩1 小时前
Leetcode 15三题之和
算法·leetcode·职场和发展
2301_793804692 小时前
C++中的适配器模式变体
开发语言·c++·算法
x_xbx2 小时前
LeetCode:206. 反转链表
算法·leetcode·链表
abant22 小时前
leetcode 138 复制随机链表
算法·leetcode·链表
旖-旎3 小时前
二分查找(1)
c++·算法·二分查找·力扣·双指针
tankeven4 小时前
HJ132 小红走网格
c++·算法
做怪小疯子4 小时前
Leetcode刷题——8.重叠区间
算法·leetcode·职场和发展
2401_857865234 小时前
C++模块接口设计
开发语言·c++·算法
add45a4 小时前
嵌入式C++低功耗设计
开发语言·c++·算法