拓扑排序实例

本文通过两个课程安排的问题,Course Schedule 和 Course Schedule II,探讨了拓扑排序在解决这类问题中的应用。文章提供了问题背景,指出课程之间的先修关系,并给出了递归和非递归的解决方案,强调了输入是以边表示的图而不是邻接矩阵。
摘要由CSDN通过智能技术生成

在前面的文章《深度优先搜索》中介绍了拓扑排序,在《深度优先实现拓扑排序--java》中给出了一种Java实现,其实现方式是从出度为0的点(也就是它不依赖任何其他点)逆向遍历的。其实还可以正向遍历,过程在前一篇文章的伪代码中给出。这里看两道相关题目加深理解应用。

1.Course Schedule

There are a total of n courses you have to take, labeled from0 ton - 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 prerequisitepairs, 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值