🥲Taking courses
给定一系列课程,一些是另一些的prerequistes,已知选了一些课,求还需要哪些课程才能上到目标课程
题目本身不难,但是很容易被误认为是拓扑排序题。首先需要意识到的是给出的taken一定是连续的而且是从初始课程开始,不可能出现需要上1才能上2但是2在taken里1却不在。同时如果使用拓扑排序会很不好解,因为拓扑排序是一种多源的bfs,所以会遍历到并不需要上的课程,正确的思路应该是从target课程倒推需要上哪些课程。
'''
Given some courses, some are prerequisites of others, and a list of courses already taken, and the target course
return the courses still needs taken
'''
from collections import defaultdict, deque
def GetCourses(courses, taken, target):
graph = defaultdict(list)
for course in courses:
graph[course[1]].append(course[0])
q = deque([target])
visited = set([target])
ans = []
while q:
course = q.popleft()
ans.append(course)
for next in graph[course]:
if next not in visited and next not in taken:
q.append(next)
visited.add(next)
return ans
'''
test case:
1 -> 2 -> 3 ->
-> 4 -> 5
6 -> 7
'''
courses = [[1,2],[2,3],[2,4],[4,5],[3,5], [6,7]]
taken = set([1, 2, 4])
print(GetCourses(courses, taken, 5))
```
Last updated