Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
- prereq_map = collections.defaultdict(list)
- indegree = collections.defaultdict(int)
- for crs, prereq in prerequisites:
- # build the adjancency list
- prereq_map[crs].append(prereq)
- # Record each node's in-degree
- indegree[prereq] += 1
- # Queue for maintainig list of nodes that have 0 in-degree
- q = deque([k for k in range(numCourses) if k not in indegree])
- output = []
- # Until there are nodes in the Q
- while q:
- # Pop one node with 0 in-degree
- node = q.popleft()
- output.append(node)
- # Reduce in-degree for all the neighbors
- for nei in prereq_map[node]:
- indegree[nei] -= 1
- # Add neighbor to Q if in-degree becomes 0
- if indegree[nei] == 0:
- q.append(nei)
- return reversed(output) if len(output) == numCourses else []
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement