Course Schedule
Course Schedule II (LC.210)
There are n courses a student has to take, labeled from 0 to n-1. Some courses have prerequisites. For example, [0,1] you have take course 1 before taking course 0. Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. In short,
Given n nodes and a list of directed edges, find one topological ordering.
Return any correct ordering is fine. If it is impossible to finish all courses, return an empty array.
Example
Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0, 1, 2, 3] or [0, 2, 1, 3]Assume no duplicate edges.
Analysis
BFS is easier to implement than a DFS on this edge list structure. Create a Map to store the indegree for each node. Also, we want to convert the edge lists to adjacency lists so we know their neighbors. Then just do topological sort.
Approach
Step 1 Build a graph
Step 2 topo sort with BFS
- count indegree
- put 0 indegree (no incoming edges) to queue
- delete that node from the queue and all its outgoing edges (decrease the indegree of its neighbor)Clear Version
Short Version
Last updated