Problem
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.
Algorithm
Topological sorting.
Code
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
table = [[0] * numCourses for i in range(numCourses)]
indeg = [0] * numCourses
for i in range(len(prerequisites)):
table[prerequisites[i][1]][prerequisites[i][0]] = 1
indeg[prerequisites[i][0]] += 1
ans = []
for i in range(numCourses):
id = -1
for j in range(numCourses):
if not indeg[j]:
id = j
break
if -1 == id:
return []
else:
ans.append(id)
for j in range(numCourses):
if table[id][j]:
table[id][j] = 0
indeg[j] -= 1
indeg[id] = -1
return ans
402

被折叠的 条评论
为什么被折叠?



