Advertisement
smj007

Untitled

Aug 26th, 2023 (edited)
1,136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. # memoization using array
  2. class Solution:
  3.     def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
  4.  
  5.         # DP with memoization
  6.         # state: 0 - unvisited
  7.         # state: 1 - visited but not finished
  8.         # state: 2 - visited and finished
  9.         visit = [0]*numCourses
  10.         from collections import defaultdict
  11.         mapping = defaultdict(list)
  12.         for (crs, prereq) in prerequisites:
  13.             mapping[crs].append(prereq)
  14.  
  15.         result = []
  16.  
  17.         def dfs(course):
  18.             if visit[course] == 1:
  19.                 return False
  20.  
  21.             if visit[course] == 2:
  22.                 return True
  23.  
  24.             visit[course] = 1
  25.  
  26.             for neighbour in mapping[course]:
  27.                 run = dfs(neighbour)
  28.                 if run is False:
  29.                     return False
  30.  
  31.             visit[course] = 2
  32.             result.append(course)
  33.             return True
  34.  
  35.         for crs in range(numCourses):
  36.             run = dfs(crs)
  37.             if run is False:
  38.                 return []
  39.  
  40.         return result
  41.  
  42. # memoization using set
  43. class Solution:
  44.     def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
  45.  
  46.         prereq_map = collections.defaultdict(list)
  47.         for crs, prereq in prerequisites:
  48.             prereq_map[crs].append(prereq)
  49.  
  50.         output = []
  51.         visit, cycle = set(), set()
  52.  
  53.         # visit counter takes care of whether a node has been added to output
  54.         # cycle counter takes care of whether a node is already part of the "current" cycle
  55.         # once you are at ending point of a possible cycle, you return
  56.         def dfs(crs):
  57.             if crs in cycle:
  58.                 return False
  59.             if crs in visit:
  60.                 return True
  61.             cycle.add(crs)
  62.             for pre in prereq_map[crs]:
  63.                 if dfs(pre) == False:
  64.                     return False
  65.             cycle.remove(crs)
  66.             visit.add(crs)
  67.             output.append(crs)
  68.             return True
  69.  
  70.         for c in range(numCourses):
  71.             if dfs(c) == False:
  72.                 return []
  73.  
  74.         return output
  75.  
  76.            
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement