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;
    }
相关推荐
矢志航天的阿洪17 分钟前
蒙特卡洛树搜索方法实践
算法
UnderTheTime1 小时前
2025 XYD Summer Camp 7.10 筛法
算法
zstar-_1 小时前
Claude code在Windows上的配置流程
笔记·算法·leetcode
圆头猫爹1 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划
秋说1 小时前
【PTA数据结构 | C语言版】出栈序列的合法性
c语言·数据结构·算法
用户40315986396631 小时前
多窗口事件分发系统
java·算法
用户40315986396631 小时前
ARP 缓存与报文转发模拟
java·算法
hi0_62 小时前
03 数组 VS 链表
java·数据结构·c++·笔记·算法·链表
aPurpleBerry2 小时前
hot100 hot75 栈、队列题目思路
javascript·算法
卷福同学3 小时前
【AI编程】AI+高德MCP不到10分钟搞定上海三日游
人工智能·算法·程序员