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;
    }
};
相关推荐
lvwangshu20 分钟前
方阵游戏 题解
题解·技巧·前缀优化·性质题·思维好题·推导题
丰色木夕28 分钟前
Ubuntu22.04下源码编译安装USD-Brep
c++·ubuntu·nvidia·usd-brep
文丑颜不良啊34 分钟前
LeetCode51~75题目解析
leetcode
学电子她就能回来吗1 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
衍玊3 小时前
多路转接原理与应用
c++
himobrinehacken5 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
文丑颜不良啊6 小时前
LeetCode1~50题目解析
leetcode
Pniubi6 小时前
力扣146.LRU缓存机制
算法·leetcode·缓存
Android小码家7 小时前
Vehicle 实战 自定义属性+测试demo
java·c++·framework·vhal·vehicle
hetao17338377 小时前
2026-10-19 hetao1733837 的刷题记录
c++·算法