-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCourseSchedule_v0.py
More file actions
43 lines (33 loc) · 955 Bytes
/
CourseSchedule_v0.py
File metadata and controls
43 lines (33 loc) · 955 Bytes
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
#!/usr/bin/env python
# encoding: utf-8
from collections import defaultdict
class Solution:
# @param {integer} numCourses
# @param {integer[][]} prerequisites
# @return {boolean}
def canFinish(self, numCourses, prerequisites):
d = defaultdict(list)
for i in prerequisites:
f, t = i
d[f].append(t)
for i in range(numCourses):
if not self.dfs(d, i):
return False
return True
def dfs(self, d, start):
stack = [start]
visited = set([])
while stack:
n = stack.pop()
if n not in visited:
visited.add(n)
else:
return False
ts = d.get(n, [])
for t in ts[::-1]:
stack.append(t)
return True
if __name__ == '__main__':
s = Solution()
print s.canFinish(2, [[1,0]])
print s.canFinish(2, [[1,0],[0,1]])