Advertisement
smj007

Untitled

Aug 26th, 2023
1,044
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. class Solution:
  2.     def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
  3.  
  4.         prereq_map = collections.defaultdict(list)
  5.         indegree = collections.defaultdict(int)
  6.        
  7.         for crs, prereq in prerequisites:
  8.             # build the adjancency list
  9.             prereq_map[crs].append(prereq)
  10.             # Record each node's in-degree
  11.             indegree[prereq] += 1
  12.  
  13.         # Queue for maintainig list of nodes that have 0 in-degree
  14.         q = deque([k for k in range(numCourses) if k not in indegree])    
  15.         output = []
  16.  
  17.         # Until there are nodes in the Q
  18.         while q:
  19.             # Pop one node with 0 in-degree
  20.             node = q.popleft()
  21.             output.append(node)
  22.  
  23.             # Reduce in-degree for all the neighbors
  24.             for nei in prereq_map[node]:
  25.                 indegree[nei] -= 1
  26.  
  27.                 # Add neighbor to Q if in-degree becomes 0
  28.                 if indegree[nei] == 0:
  29.                     q.append(nei)
  30.  
  31.         return reversed(output) if len(output) == numCourses else []
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement