207&210. Course Schedule I&II

207。Course Schedule I

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return true if you can finish all courses. Otherwise, return false.

Example 1:

Input: numCourses = 2, prerequisites = [[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: numCourses = 2, prerequisites = [[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.

Constraints:

  • 1 <= numCourses <= 2000

  • 0 <= prerequisites.length <= 5000

  • prerequisites[i].length == 2

  • 0 <= ai, bi < numCourses

  • All the pairs prerequisites[i] are unique.

My Solutions:

用一个visited[]数组,记录每一个节点的状态。其中visited[i]的值:0 代表还未访问的状态; 1 代表正在访问的状态; 2 代表已经访问完成。

如果当前访问节点的状态为1,说明该节点正在递归访问其后续节点,此时再次回到当前节点时,只能说明递归访问路径出现了环路(比如课程A的先修课是B,此时A的状态为1,递归到B时发现其先修课为A,再递归到A时发现其状态为1,这就是回路。),这是不能满足条件的情况,可以直接返回false。

一门课程C,其先修课为A,如果A的转态是2,说明已经访问过A,并且没有回路

210。Course Schedule II

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Example 1:

Example 2:

Example 3:

和上题类似,但要返回先修课程

My Solutions:

解法和上题类似,但因为要返回先修课程,需要在dfs的时候加入一个list,在每判断完一个节点和将visited数组更新为2时,把这个点加入到返回的list中。

dfs可能造成stack overflow. 用bfs这样写

Last updated