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;
    }
相关推荐
圣保罗的大教堂4 小时前
leetcode 3867. 数对的最大公约数之和 中等
leetcode
To_OC6 小时前
LC 15 三数之和:双指针不难,难的是把去重做对
javascript·算法·leetcode
renhongxia18 小时前
世界模型,是“空中楼阁”还是AGI的“最后一块拼图”?
运维·服务器·数据库·人工智能·算法·agi
G.O.G.O.G9 小时前
LeetCode SQL 从入门到精通(MySQL)06(上)
数据库·sql·mysql·leetcode
zephyr0510 小时前
动态规划-最长上升子序列问题
算法·动态规划
闪电悠米11 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
卡提西亚12 小时前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结12 小时前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
从零开始的代码生活_13 小时前
C++ 多态详解:虚函数、动态绑定、抽象类与虚表原理
开发语言·c++·后端·学习·算法
Tisfy13 小时前
LeetCode 3867.数对的最大公约数之和:按题目说的做(gcd)
算法·leetcode·题解·模拟·最大公约数·gcd