53、图论-课程表

思路:

其实就是图的拓扑排序,我们可以构建一个图形结构,比如[0,1]表示1->0,对于0来说入度为+1。

遍历结束后,从入度为0的开始遍历。引文只有入度为0的节点没有先决条件。然后依次减少1。直到所有节点入度都为0.然后记录下来count和需要学习课程数相比如果相等表示可以。不相等表示存在环。

java 复制代码
class Solution {
   public static class Node {
        public int name;
        public int in;
        public ArrayList<Node> nexts;

        public Node(int n) {
            name = n;
            in = 0;
            nexts = new ArrayList<>();
        }
    }

    public static boolean canFinish(int numCourses, int[][] prerequisites) {
        if (prerequisites == null || prerequisites.length == 0) {
            return true;
        }
        Map<Integer, Node> nodes = new HashMap<>();
        for (int[] arr : prerequisites) {
            //目标课程编号
            int to = arr[0];
            //前驱课程编号
            int from = arr[1];
            if (!nodes.containsKey(to)) {
                nodes.put(to, new Node(to));
            }
            if (!nodes.containsKey(from)) {
                nodes.put(from, new Node(from));
            }
            //获取目标课程 节点
            Node t = nodes.get(to);
            Node f = nodes.get(from);
            //表示前驱课程指向目标课程  就是图的有向指标
            f.nexts.add(t);
            //目标课程入度++
            t.in++;
        }
        int needPrerequisiteNums = nodes.size();
        //建立一个入度为0 队列 表示这个是起始节点
        Queue<Node> zeroInQueue = new LinkedList<>();
        for (Node node : nodes.values()) {
            if (node.in == 0) {
                zeroInQueue.add(node);
            }
        }
        int count = 0;
        //拓扑排序  一次减少入度  如果count!=needPrerequisiteNums 说明有环,循环依赖 
        while (!zeroInQueue.isEmpty()) {
            Node cur = zeroInQueue.poll();
            count++;
            for (Node next : cur.nexts) {
                if (--next.in == 0) {
                    zeroInQueue.add(next);
                }
            }
        }
        return count == needPrerequisiteNums;
    }
}
相关推荐
怀旧诚子28 分钟前
timeshift之Fedora43设置,已在VM虚拟机验证,待真机验证。
java·服务器·数据库
1104.北光c°33 分钟前
滑动窗口HotKey探测机制:让你的缓存TTL更智能
java·开发语言·笔记·程序人生·算法·滑动窗口·hotkey
云原生指北3 小时前
GitHub Copilot SDK 入门:五分钟构建你的第一个 AI Agent
java
仰泳的熊猫5 小时前
题目2570:蓝桥杯2020年第十一届省赛真题-成绩分析
数据结构·c++·算法·蓝桥杯
Leinwin8 小时前
OpenClaw 多 Agent 协作框架的并发限制与企业化规避方案痛点直击
java·运维·数据库
无极低码8 小时前
ecGlypher新手安装分步指南(标准化流程)
人工智能·算法·自然语言处理·大模型·rag
薛定谔的悦8 小时前
MQTT通信协议业务层实现的完整开发流程
java·后端·mqtt·struts
软件算法开发8 小时前
基于海象优化算法的LSTM网络模型(WOA-LSTM)的一维时间序列预测matlab仿真
算法·matlab·lstm·一维时间序列预测·woa-lstm·海象优化
enjoy嚣士8 小时前
springboot之Exel工具类
java·spring boot·后端·easyexcel·excel工具类