-
Notifications
You must be signed in to change notification settings - Fork 2
/
sol.py
55 lines (41 loc) · 1.34 KB
/
sol.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from typing import Counter, List
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = self.getGraph(prerequisites)
res = self.isCyclic(graph)
return not res
def isCyclic(self, graph) -> bool:
visited = {}
nest = {}
def dfs(node):
if node in visited:
return False
if node not in graph:
return False
visited[node] = True
nest[node] = True
for child in graph[node]:
if child in nest:
return True
if dfs(child):
return True
del nest[node]
for node in graph:
if node in visited:
continue
if dfs(node):
return True
return False
def getGraph(self, prerequisites: List[List[int]]):
connections = {}
for dependee, dependor in prerequisites:
if dependor not in connections:
connections[dependor] = {}
connections[dependor][dependee] = True
return connections
numCourses = 2
prerequisites = [[1,0]]
# prerequisites = [[1,0],[0,1]]
s = Solution()
res = s.canFinish(numCourses, prerequisites)
print(res)