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;
    }
相关推荐
贾斯汀玛尔斯7 小时前
每天学一个算法--LSM-Tree(Log-Structured Merge Tree)
java·算法·lsm-tree
浅念-11 小时前
刷穿LeetCode:BFS 解决 Flood Fill 算法
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
做cv的小昊12 小时前
【TJU】研究生应用统计学课程笔记(8)——第四章 线性模型(4.1 一元线性回归分析)
笔记·线性代数·算法·数学建模·回归·线性回归·概率论
贾斯汀玛尔斯13 小时前
每天学一个算法--倒排索引(Inverted Index)
算法·inverted-index
小e说说13 小时前
打破偏科困境:这些学习软件助孩子重燃学习热情
算法
我命由我1234513 小时前
程序员的心理学学习笔记 - 空杯心态
经验分享·笔记·学习·职场和发展·求职招聘·职场发展·学习方法
月昤昽13 小时前
autoCAD二次开发 4.正多边形与collection区分
算法·c#·二次开发·autocad二次开发
休息一下接着来13 小时前
C++ 固定容量环形队列实现
c++·算法
im_AMBER14 小时前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵