LeetCode【207】课程表

题目:

思路:

https://www.jianshu.com/p/25868371ddfc/

代码:

java 复制代码
public boolean canFinish(int numCourses, int[][] prerequisites) {
        // 入度
        int[] indegress = new int[numCourses];

        // 每个点对应的边,出边
        Map<Integer, List<Integer>> adjacency = new HashMap<>();

        Queue<Integer> queue = new LinkedList<>();

        for (int i = 0; i < numCourses; i++) {
            adjacency.put(i, new ArrayList<>());
        }

        for (int[] cp : prerequisites) {
            indegress[cp[0]]++;
            adjacency.get(cp[1]).add(cp[0]);
        }

        for (int i = 0; i < numCourses; i++) {
            if (indegress[i] == 0) {
                queue.offer(i);
            }
        }

        // BFS
        while (!queue.isEmpty()) {
            Integer pre = queue.poll();
            numCourses--;
            for (int cur : adjacency.get(pre)) {
                if (--indegress[cur] == 0) {
                    queue.offer(cur);
                }
            }
        }

        return numCourses == 0;
    }
相关推荐
故事和你914 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__4 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__5 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒6 小时前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣6 小时前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮6 小时前
Opus 4.7 来了,我并不建议你升级
算法
无敌昊哥战神7 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__7 小时前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode