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?Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: 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.
You may assume that there are no duplicate edges in the input prerequisites.

  • 思路
    修读课程,给定多组序列[a, b],表示要学习a课程必须先学习b课程。问是否可以全部修完n门课程?题目链接
    拓扑排序。统计每个点(课程)的入度,然后把入度为0的入队。再依次出队,每出队一次课程数减一,然后将该点的后续点入度减一,如果为0则入队。最后课程数为0表示可以全部修完。补充:当需要输出正确的序列时,可以在每次出队的时候记录该点,最后判断是否能修完,若能的话返回结果
import java.util.LinkedList;

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {

        // 统计所有点的入度
        int[] inDegrees = new int[numCourses];
        for(int[] arr : prerequisites){
            inDegrees[arr[0]] ++;
        }

        // 将入度为0的点加入队列
        LinkedList<Integer> queue = new LinkedList<Integer>();
        for(int i=0; i<numCourses; i++){
            if(inDegrees[i] == 0){
                queue.add(i);
            }
        }

        // 依次出队消除关系
        while( !queue.isEmpty()){
            int pre = queue.poll();
            numCourses --; // 注意每出队一次节点数减1
            for(int[] arr : prerequisites){
                if(arr[1] != pre){ // 当起点不是pre时跳过
                    continue;
                }
                if(--inDegrees[arr[0]] == 0){ // 入度减1然后判断是否可以入队
                    queue.add(arr[0]);
                }
            }
        }

        return numCourses == 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值