[leetcode-207]Course Schedule(java)

问题描述:
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.

分析:这道题主要是看课程之间是否存在相互依赖关系,从图论角度见是否构成环。
环的入度永远不会为0,因此,本题的思想是先找出入度为0的点,然后加入到list中,然后从list中弹出,获取元素的相临节点(通过map),然后将对应节点的入度–,当为0时,加入到list中。
当list为空时,此时如果还有num不为-1,未处理,那么就表示课程之间存在环。返回false;

代码如下:400ms

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        HashMap<Integer,List<Integer>> maps = new HashMap<>();
        int[] indegree = new int[numCourses];

        int length = prerequisites.length;
        if(length<=0)
            return true;
        //init Map

        for(int i = 0;i<length;i++){
            int first = prerequisites[i][0];
            int second = prerequisites[i][1];
            if(!maps.containsKey(first))
                maps.put(first,new LinkedList<>());
            maps.get(first).add(second);
            indegree[second]++;
        }

        List<Integer> list = new LinkedList();
        for(int i = 0;i<numCourses;i++){
            if(indegree[i]==0)
                list.add(i);
        }
        while(list.size()>0){
            int val = list.get(0);
            indegree[val] = -1;
            list.remove(0);
            if(!maps.containsKey(val))
                continue;

            List<Integer> tmpList = maps.get(val);
            for(int i = 0;i<tmpList.size();i++){
                int index = tmpList.get(i);
                indegree[index]--;
                if(indegree[index]==0)
                    list.add(index);
            }
        }
        for(int i = 0;i<numCourses;i++)
            if(indegree[i]!=-1)
                return false;

        return true;

    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值