210 Course Schedule II
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].import collections
class Solution:
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
# create directed graph
g = {course: set() for course in range(0, numCourses)}
for pair in prerequisites:
g[pair[0]].add(pair[1])
sol = []
def topological_sort():
for course, dependances in g.items():
if len(dependances) is 0:
sol.append(course)
del g[course]
for _, dependances2 in g.items():
if dependances2.__contains__(course):
dependances2.remove(course)
return topological_sort()
topological_sort()
return sol if not any(g) else []
obj = Solution()
print(obj.findOrder(2, [[0,1],[1,0]]))
print(obj.findOrder(2, [[1,0]]))
print(obj.findOrder(4, [[1,0],[2,0],[3,1],[3,2]]))Last updated