1 此问题等同于有向图检测环,vertex是course,edge是prerequisite,一般会使用topological sorting拓扑排序来检测。一个有向图如果有环则不存在topological order
2 常用的topological sort有两种:
Kahn's Algorithm:BFS based, start from vertices with 0 incoming edge, insert them into list S, at the same time, we remove all outgoing edges, after that find new vertices with 0 incoming edges and so on
Tarjan's Algorithm: DFS based, loop through each node of the graph in an arbitrary order, initiating a depth-first search that terminates when it hits any node that has already been visited since the beginning of the topological sort or the node has no outgoing edges
3 这道题本质是给我们一个图,看这个图是不是拓扑序列
4 在初始的图中,入度为0的点,即是课程中最基础的课程(比如数据结构,c语言基础)
红框中的很重要,可以减少很多多余的check
Time complexity: O(V+E) because we search each vertices and edges exactly once in this solution
space complexity: O(E) E是edges数
The usual algorithms for topological sorting have running time linear in the number of nodes plus the number of edges
Time complexity: O(n)
Space complexity: O(n)