力扣HOT100 - 207. 课程表

解题思路:

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] inDegree = new int[numCourses];//存每个结点的入度
        List<List<Integer>> res = new ArrayList<>();//存结点之间依赖关系
        Queue<Integer> queue = new LinkedList<>();
        //初始化二维List集合
        for(int i = 0; i < numCourses; i++)
            res.add(new ArrayList<>());
        //取出每一对结点
        for(int[] temp : prerequisites){
            inDegree[temp[0]]++;
            res.get(temp[1]).add(temp[0]);
        }
        
        //先把所有入度为0的结点加入队列
        for(int i = 0; i < numCourses; i++)
            if(inDegree[i] == 0) 
                queue.add(i);

        while(!queue.isEmpty()){
            int pre = queue.poll();
            numCourses--;
            //根据依赖关系,把入度-1
            for(int cur : res.get(pre)){
                if(--inDegree[cur] == 0)
                    queue.add(cur);
            }
        }
        return numCourses == 0;
    }
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-29 22:08:07       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-29 22:08:07       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-29 22:08:07       87 阅读
  4. Python语言-面向对象

    2024-04-29 22:08:07       96 阅读

热门阅读

  1. 如何Vue.js 结合 Element UI 进行表单验证

    2024-04-29 22:08:07       35 阅读
  2. springboot之Conditional相关注解

    2024-04-29 22:08:07       29 阅读
  3. Linux系统——HTTP常见面试题

    2024-04-29 22:08:07       25 阅读
  4. React 之 内置方法setState改变state(一)

    2024-04-29 22:08:07       34 阅读
  5. ros收发话题通信测试

    2024-04-29 22:08:07       32 阅读
  6. 2024-04-29 区块链-项目-记录

    2024-04-29 22:08:07       34 阅读
  7. flume配置

    2024-04-29 22:08:07       34 阅读
  8. python绘制三维散点图

    2024-04-29 22:08:07       35 阅读
  9. 嵌入式学习——C语言基础——day12

    2024-04-29 22:08:07       38 阅读
  10. Python学习路线图及开源库和工具推荐

    2024-04-29 22:08:07       25 阅读