Leetcode207. 课程表(HOT100)

链接

题解:先统计入度为0的点,如果一个节点入度为0,说明没有课程指向它,那么你就可以学习它了。反之说明还有先修课。

注意:图存在拓扑排序等价于图不存在环。其实可以想出:如果是一个环,那么就没有突破点。

代码:

cpp 复制代码
class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        int n = numCourses;//可以直接改变形参为n,方便代码书写
        vector<vector<int>> g(n);
        vector<int> d(n);
        for(const auto&e:prerequisites){
            int b = e[0],a = e[1];
            g[a].push_back(b);
            d[b]++;
        }
        queue<int> q;
        for(int i = 0;i<n;i++){
            if(d[i]==0){
                q.push(i);
            }
        }
        
        int cnt = 0;
        while(q.size()){
            int a = q.front();
            q.pop();
            cnt++;
            for(const auto&e:g[a]){
                if(--d[e]==0){
                    q.push(e);
                }
            }

        }
        return cnt==n;
    }
};

题解:

相关推荐
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1231 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long2 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn2 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap