LeetCode之Graph题目汇总

本文汇总了LeetCode中的Graph题目,包括Course Schedule和Course Schedule II。这两道题都是关于课程先修关系的,需要判断是否存在完成所有课程的顺序,或者给出一个可行的课程顺序。题目关键在于检测图中是否有环,并实现拓扑排序。解决方案可以通过BFS或DFS实现。当没有先修条件(prerequisites为空)时,可自由排列课程顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note: 
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.


题目等价为:检测图中是否有环

参考网址:LeetCode – Course Schedule (Java)

BFS:

    // BFS
    public static boolean canFinish(int numCourses, int[][] prerequisites) {

        // 参数检查
        if (prerequisites == null) {
            return false;
        }

        int len = prerequisites.length;
        if (numCourses <= 0 || len == 0) {
            return true;
        }

        // 记录每个course的prerequisites的数量
        int[] pCounter = new int[numCourses];
        for (int i = 0; i < len; i++) {
            pCounter[prerequisites[i][0]]++;
        }

        // 用队列记录可以直接访问的course
        LinkedList<Integer> queue = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值