博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
48.Course Schedule(课程安排)
阅读量:5098 次
发布时间:2019-06-13

本文共 1421 字,大约阅读时间需要 4 分钟。

Level:

  Medium

题目描述:

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: trueExplanation: 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: falseExplanation: 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:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about .
  2. You may assume that there are no duplicate edges in the input prerequisites.

思路分析:

  这题是拓扑排序一道应用,首先,我们应该统计每个点的入度,然后根据拓扑排序的规则,先删去入度为0的点,直到最后点的个数为0,则是正确的排课。

代码:

public class Solution{    public boolean canFinish(int coursenum,int[][]prerequisites){        int []indegree=new int [coursenum];//记录每门课的入度。        for(int []pair:prerequisites){            indegree[pair[0]]++; //统计每门课的入度        }        Queue
q=new LinkedList<>(); //存放入度为0的课程,准备删除 for(int i=0;i

转载于:https://www.cnblogs.com/yjxyy/p/11087403.html

你可能感兴趣的文章
Bootstrap栅格学习
查看>>
程序员的数学
查看>>
聚合与组合
查看>>
洛谷 P2089 烤鸡【DFS递归/10重枚举】
查看>>
我眼中的技术地图
查看>>
lc 145. Binary Tree Postorder Traversal
查看>>
在centos上开关tomcat
查看>>
android dialog使用自定义布局 设置窗体大小位置
查看>>
ionic2+ 基础
查看>>
查询消除重复行
查看>>
[leetcode]Minimum Path Sum
查看>>
内存管理 浅析 内存管理/内存优化技巧
查看>>
Aizu - 1378 Secret of Chocolate Poles (DP)
查看>>
csv HTTP简单表服务器
查看>>
IO流写出到本地 D盘demoIO.txt 文本中
查看>>
Screening technology proved cost effective deal
查看>>
mysql8.0.13下载与安装图文教程
查看>>
Thrift Expected protocol id ffffff82 but got 0
查看>>
【2.2】创建博客文章模型
查看>>
Kotlin动态图
查看>>