力扣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;
    }
};
相关推荐
GalaxyPokemon20 分钟前
归并排序:分治思想的高效排序
数据结构·算法·排序算法
ThreeYear_s22 分钟前
基于FPGA的PID算法学习———实现PI比例控制算法
学习·算法·fpga开发
Coding小公仔3 小时前
LeetCode 240 搜索二维矩阵 II
算法·leetcode·矩阵
C++chaofan3 小时前
74. 搜索二维矩阵
java·算法·leetcode·矩阵
Studying 开龙wu4 小时前
机器学习监督学习实战五:六种算法对声呐回波信号进行分类
学习·算法·机器学习
Mi Manchi264 小时前
力扣热题100之二叉树的层序遍历
python·算法·leetcode
wu~9704 小时前
leetcode:42. 接雨水(秒变简单题)
算法·leetcode·职场和发展
zhurui_xiaozhuzaizai5 小时前
模型训练-关于token【低概率token, 高熵token】
人工智能·算法·自然语言处理
ThreeYear_s5 小时前
基于FPGA的PID算法学习———实现PID比例控制算法
学习·算法·fpga开发