-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path207.CourseSchedule.py
40 lines (33 loc) · 1.05 KB
/
207.CourseSchedule.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
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
[[1,0],[0,1]]
numCourses = 2, prerequisites = [[1,0],[0,1]]
"""
# what is this
preMap = {i : [] for i in range(numCourses)}
for node, pre in prerequisites:
preMap[pre].append(node)
visited = set()
def dfs(start):
if not preMap[start]:
return True
if start in visited:
return False
visited.add(start)
for pre in preMap[start]:
if not dfs(pre):
return False
visited.remove(start)
preMap[start] = []
return True
for i in range(numCourses):
if not dfs(i):
return False
return True
s = Solution()
res = s.canFinish(numCourses = 2, prerequisites = [[1,0],[0,1]])
print(res)