Course Schedule II

LeetCode: https://leetcode.com/problems/course-schedule-ii/

Return the ordering of courses you should take to finish all courses. If impossible, return an empty array.

1from collections import deque
2
3def findOrder(numCourses: int, prerequisites: List[List[int]]) -> List[int]:
4 graph = [[] for _ in range(numCourses)]
5 indeg = [0] * numCourses
6 for a, b in prerequisites:
7 graph[b].append(a)
8 indeg[a] += 1
9
10 q = deque([i for i in range(numCourses) if indeg[i] == 0])
11 order = []
12
13 while q:
14 cur = q.popleft()
15 order.append(cur)
16 for nxt in graph[cur]:
17 indeg[nxt] -= 1
18 if indeg[nxt] == 0:
19 q.append(nxt)
20
21 return order if len(order) == numCourses else []
0
0
1
1
2
2
3
3
numCourses=4
prerequisites=Array(4)
graph=Array(4)
indeg=[0, 1, 1, 2]
Step 1 / 6
Step 1:
Build graph and indeg for prerequisites [[1,0],[2,0],[3,1],[3,2]].
Focus: select @ [0]
numCourses=4