leetcode课程表-207-拓扑排序

本文介绍了一个Java解决方案,用于解决LeetCode中的课程表问题(第207题),通过拓扑排序算法判断在有限的课程依赖关系下能否完成所有课程。

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


import java.util.*;
class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int num=0;num< numCourses;num++) map.put(num,0);
        Map<Integer,List<Integer>> con = new HashMap<>();

        //初始化记录数,地图由拥有入读的Map类型来记录
        for(int[] arr : prerequisites){
            List<Integer> nextList = con.get(arr[1]);
            if(nextList == null) {
                nextList = new LinkedList<>();
                con.put(arr[1],nextList);
            }

            int inp = map.get(arr[0]);
            map.put(arr[0],inp + 1);
            nextList.add(arr[0]);
        }

        LinkedList<Integer> queue = new LinkedList<>();

        //初始化先决条件
        for(int num=0;num< numCourses;num++){
            if(map.get(num) == 0) queue.add(num);
        }


        //通过先决条件来开路
        while(queue.size() != 0){
            int pre = queue.removeLast();
            List<Integer> nextList = con.get(pre);

            if(nextList == null) continue;
            for(int next : nextList){
                int inp = map.get(next) - 1;
                map.put(next,inp);
                if(inp == 0) queue.add(next);
            }
        }

        for(int num=0;num< numCourses;num++){
            if(map.get(num) != 0) return false;
        }
        return true;
   }
}

leetcode课程表-207-拓扑排序

没想象的难。就这样吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值