力扣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;
    }
};
相关推荐
Nazarick1 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴1 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴2 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_113 小时前
算法札记:有限差分
算法
忙里偷闲学python3 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农3 小时前
11.21程序设计
数据结构·算法
Tisfy4 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6174 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
灯澜忆梦5 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
Shaoshing6 小时前
LeetCode100 155.最小栈
java·数据结构·算法