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;
    }
};

题解:

相关推荐
数智工坊3 小时前
【数据结构-树与二叉树】4.6 树与森林的存储-转化-遍历
数据结构
望舒5133 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
独好紫罗兰3 小时前
对python的再认识-基于数据结构进行-a006-元组-拓展
开发语言·数据结构·python
铉铉这波能秀3 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
踢足球09294 小时前
寒假打卡:2026-2-8
数据结构·算法
老赵说4 小时前
Java基础数据结构全面解析与实战指南:从小白到高手的通关秘籍
数据结构
铉铉这波能秀4 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
静听山水5 小时前
Redis核心数据结构-ZSet
数据结构·redis
铉铉这波能秀5 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
Queenie_Charlie5 小时前
stars(树状数组)
数据结构·c++·树状数组