1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| from typing import List from collections import defaultdict from collections import deque
def findOrder(numCourses: int, prerequisites: List[List[int]]) -> List[int]: # construct two-way table courses = defaultdict(set) # {course:prerequests} pres = defaultdict(set) # {prerequests:course} for course, pre in prerequisites: courses[course].add(pre) pres[pre].add(course) print("courses: ",courses) print("pres: ",pres) # find start point(no pre) queue = deque() for n in range(numCourses): # list all Courses if not courses[n]: # append no pre, that's begin queue.append(n) # travel stack count,ret = 0, [] # 210 while queue: cur = queue.popleft() # FIFO, pop是LIFO print(cur) ret.append(cur) # 210 count+=1 for course in pres[cur]: # find next course courses[course].remove(cur) # remove previous course if not courses[course]: # if no previous queue.append(course) # append next course to find return ret if count==numCourses else [] # 210 print(findOrder(4, [[1,0], [2,0], [3,1], [3,2]]))
> [0, 2, 1, 3] or [0, 1, 2, 3]
|