力扣hot100:207. 课程表

这是一道拓扑排序问题,也可以使用DFS判断图中是否存在环。详情请见:官方的BFS算法请忽略,BFS将问题的实际意义给模糊了,不如用普通拓扑排序思想。

数据结构:图的拓扑排序与关键路径

拓扑排序:

cpp 复制代码
class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> degree(numCourses,0);
        vector<vector<int>> g(numCourses);
        int top=-1;
        int num=0;
        for(auto i:prerequisites){
            g[i[1]].emplace_back(i[0]);
            degree[i[0]]++;
        }
        for(int i=0;i<numCourses;++i) if(degree[i]==0) {degree[i]=top;top=i;num++;}
        while(top!=-1){
            int pre=top;top=degree[top];
            for(auto i:g[pre]){
                if(--degree[i]==0){
                    degree[i]=top;
                    top=i;
                    ++num;
                }
            }
        }
        return num==numCourses;
    }
};
相关推荐
HjhIron4 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩6 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹7 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术11 小时前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望13 小时前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰13 小时前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者1 天前
J6B vio scenario sample
算法
BothSavage1 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn1 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法