Course Schedule

Graph, Depth-first Search, Breadth-first Search, Topological Sorting

Medium

There are a total of n courses you have to take, labeled from0ton-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: 
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:
 2, [[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.

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

  2. You may assume that there are no duplicate edges in the input prerequisites.

Analysis

此题考虑课程依赖关系是否能满足,其实抽象来看,课程的依赖关系其实是有向图的边edge,那么问题的内核其实就是这个有向图是否有环,如果无环,则依赖关系可以成立,也就是DAG (有向无环图)。判定是否为DAG,则可以用拓扑排序Topological Sorting

https://www.youtube.com/watch?v=M6SBePBMznU

拓扑排序 = 顶点染色 + 记录顺序

这里只需要顶点染色即可。

DFS - 需要先遍历叶子节点,再遍历根节点,因此可以看成是post-order

Solution

Topological Sorting - HashMap - DFS - (9ms 83.11% AC)

*Topological Sort - DFS - Improved - ArrayList[] - (5ms 99.81% AC)

Topological Sort - OO Style - DFS (8ms 87.81% AC)

Modified from https://leetcode.com/problems/course-schedule/discuss/58713/OO-easy-to-read-java-solution

BFS

Reference

https://www.jiuzhang.com/solution/course-schedule

https://blog.csdn.net/ljiabin/article/details/45846837

https://www.youtube.com/watch?v=ddTC4Zovtbc

Last updated

Was this helpful?