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;
    }
};
相关推荐
C语言小火车1 天前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型
liulilittle1 天前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
眠りたいです1 天前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器
Want5951 天前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客1 天前
c++ 杂记
开发语言·c++
jimmy.hua1 天前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
tan180°1 天前
Boost搜索引擎 网络库与前端(4)
linux·网络·c++·搜索引擎
bkspiderx1 天前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
郝学胜-神的一滴1 天前
避免使用非const全局变量:C++中的最佳实践 (C++ Core Guidelines)
开发语言·c++·程序人生
晚云与城1 天前
今日分享:C++ Stack和queue(栈与队列)
开发语言·c++