首页 > 其他分享 >【拓扑排序】LeetCode 207. 课程表

【拓扑排序】LeetCode 207. 课程表

时间:2023-01-16 19:34:11浏览次数:65  
标签:207 int adjacency numCourses queue 课程表 indegrees cp LeetCode

题目链接

207. 课程表

思路

参考Krahets大佬的思路

image

代码

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] indegrees = new int[numCourses];
        List<List<Integer>> adjacency = new ArrayList<>();
        Queue<Integer> queue = new LinkedList<>();

        for(int i = 0; i < numCourses; i++){
            adjacency.add(new ArrayList<>());
        }
        // Get the indegree and adjacency of every course.
        for(int[] cp : prerequisites){
            indegrees[cp[0]]++;
            adjacency.get(cp[1]).add(cp[0]);
        }
        // Get all the courses with the indegree of 0.
        for(int i = 0; i < numCourses; i++){
            if(indegrees[i] == 0){
                queue.add(i);
            }
        }

        while(!queue.isEmpty()){
            int pre = queue.poll();
            numCourses--;
            for(int cur : adjacency.get(pre)){
                if(--indegrees[cur] == 0){
                    queue.add(cur);
                }
            }
        }
        
        return numCourses == 0;
    }
}

标签:207,int,adjacency,numCourses,queue,课程表,indegrees,cp,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17056164.html

相关文章

  • 代码随想录算法训练营day04 | leetcode
    基础知识记录一下栈实现及操作publicclassArrayDequeStack{publicvoidmain(){ArrayDequestack=newArrayDeque();//大小......
  • LeetCode.142 环形链表II
    1.题目:给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。如果链表中有某个节点,可以通过连续跟踪next指针再次到达,则链表中存在......
  • [LeetCode] 1813. Sentence Similarity III
    Asentenceisalistofwordsthatareseparatedbyasinglespacewithnoleadingortrailingspaces.Forexample, "HelloWorld", "HELLO", "helloworldhel......
  • 【BFS】LeetCode 417. 太平洋大西洋水流问题
    题目链接417.太平洋大西洋水流问题思路问题可以转换成从四个边界出发,能和内部哪些点连通。因为涉及到两个可达性问题,所以用两个boolean类型矩阵分别记录一个点到太......
  • 【LeetCode链表#7】设计一个链表并实现常见的操作方法
    设计链表题目力扣题目链接设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val和next。val是当前节点的值,next是指向下一个节点的指......
  • leetcode算法入门Day6---滑动窗口
    3.无重复字符的最长子串给定一个字符串s,请你找出其中不含有重复字符的最长子串的长度。测试用例:输入:s="abcabcbb"输出:3解释:因为无重复字符的最长子串......
  • LeetCode_单周赛_328
    6291.数组元素和与数字和的绝对差代码模拟即可classSolution{publicintdifferenceOfSum(int[]nums){intans=0;intsum=0;......
  • LeetCode 300_最长递增子序列
    LeetCode300:最长递增子序列题目给你一个整数数组nums,找到其中最长严格递增子序列的长度。子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素......
  • 【BFS】LeetCode 542. 01 矩阵
    题目链接542.01矩阵思路题目让求1到0的距离,其实可以转换成求0到1的距离,将所有的0作为源结点放入队列进行BFS。BFS本质上就是从源点开始的搜索算法,本题只不过是所有的......
  • 【BFS】LeetCode 1091. 二进制矩阵中的最短路径
    题目链接1091.二进制矩阵中的最短路径思路BFS找最短路模板题代码classSolution{publicintshortestPathBinaryMatrix(int[][]grid){if(grid[0][......