Advertisement
smj007

Untitled

Aug 21st, 2023 (edited)
752
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. class Solution:
  2.     def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
  3.  
  4.         from collections import defaultdict
  5.  
  6.         # make courses and add adjanceny list
  7.         premap = defaultdict(list)
  8.         for crs, pre in prerequisites:
  9.             premap[crs].append(pre)
  10.  
  11.         # all courses along the current dfs path
  12.         visit_path = set()
  13.         def dfs(crs):
  14.  
  15.             # along a path if the course is visited again
  16.             # this will be helpful in detecting a cycle
  17.             if crs in visit_path:
  18.                 return False
  19.             if premap[crs] == []:
  20.                 return True
  21.  
  22.             visit_path.add(crs)
  23.             # loop through prereqs of this course
  24.             for pre in premap[crs]:
  25.                 # if we find one course that can not be
  26.                 # completed then we can return false for the
  27.                 # entire function
  28.                 if not dfs(pre): return False
  29.  
  30.             visit_path.remove(crs)
  31.             premap[crs] = []
  32.             return True
  33.  
  34.         for crs in range(numCourses):
  35.             if not dfs(crs): return False
  36.  
  37.         return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement