Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
- from collections import defaultdict
- # make courses and add adjanceny list
- premap = defaultdict(list)
- for crs, pre in prerequisites:
- premap[crs].append(pre)
- # all courses along the current dfs path
- visit_path = set()
- def dfs(crs):
- # along a path if the course is visited again
- # this will be helpful in detecting a cycle
- if crs in visit_path:
- return False
- if premap[crs] == []:
- return True
- visit_path.add(crs)
- # loop through prereqs of this course
- for pre in premap[crs]:
- # if we find one course that can not be
- # completed then we can return false for the
- # entire function
- if not dfs(pre): return False
- visit_path.remove(crs)
- premap[crs] = []
- return True
- for crs in range(numCourses):
- if not dfs(crs): return False
- return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement