在前面的文章《深度优先搜索》中介绍了拓扑排序,在《深度优先实现拓扑排序--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