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;
    }
}
相关推荐
聪明的笨猪猪6 分钟前
Java Spring “IOC + DI”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
ThisIsMirror10 分钟前
CompletableFuture并行任务超时处理模板
java·windows·python
Young_Zn_Cu41 分钟前
LeetCode刷题记录(持续更新中)
算法·leetcode
天选之女wow1 小时前
【代码随想录算法训练营——Day31】贪心算法——56.合并区间、738.单调递增的数字、968.监控二叉树
算法·leetcode·贪心算法
lixinnnn.1 小时前
贪心:火烧赤壁
数据结构·c++·算法
小小前端_我自坚强1 小时前
前端算法相关详解
前端·算法
珹洺1 小时前
Java-Spring入门指南(二十一)Thymeleaf 视图解析器
java·开发语言·spring
源码集结号1 小时前
一套智慧工地云平台源码,支持监管端、项目管理端,Java+Spring Cloud +UniApp +MySql技术开发
java·mysql·spring cloud·uni-app·源码·智慧工地·成品系统
EnCi Zheng1 小时前
Spring Security 最简配置完全指南-从入门到精通前后端分离安全配置
java·安全·spring
程序员小假1 小时前
为什么这些 SQL 语句逻辑相同,性能却差异巨大?
java·后端