Course Schedule
Question
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:
|
|
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
|
|
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.
Analysis
先将题给的先修课程转化为图结构,利用队列不断寻找入度为0的节点,最后判断所有入度为0的节点个数是否等于numcourses
Code
|
|
Course Description II
Question
同上,输出拓扑排序结果
Analysis
注意:
- 在构建图的时候可能会存在重复的先修关系,所以需要判断该点在图中是否已为1
Code
|
|