언어: python3
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# find if cycle exists
graph = collections.defaultdict(list)
for latter,pre in prerequisites:
graph[latter].append(pre)
visited = set()
trace = set()
def dfs(i):
if i in trace:
return False
if i in visited:
return True
trace.add(i)
for pre in graph[i]:
if not dfs(pre):
return False
trace.remove(i)
visited.add(i)
return True
for key in graph.keys():
if not dfs(key):
return False
'''
for x in list(graph):
if not dfs(x):
return False
'''
return True