Advertisement
hoangreal

Parallel Courses III (DFS)

Oct 21st, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. class Solution:
  2. def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
  3.  
  4. def solve(n, relations, time):
  5. time = [0] + time
  6. # build reverse graph
  7. graph = [[] for _ in range(n+1)]
  8. for x, y in relations:
  9. graph[y].append(x)
  10.  
  11. cache = {}
  12. def dfs(course):
  13. if course in cache:
  14. return cache[course]
  15.  
  16. max_prereq_time = 0
  17. for prereq in graph[course]:
  18. max_prereq_time = max(max_prereq_time, dfs(prereq))
  19.  
  20. cache[course] = max_prereq_time + time[course]
  21. return cache[course]
  22.  
  23. return max(dfs(i) for i in range(1, n+1))
  24.  
  25. return solve(n, relations, time)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement