-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path207.course-schedule.py
58 lines (49 loc) · 1.6 KB
/
207.course-schedule.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
56
57
#
# @lc app=leetcode id=207 lang=python3
#
# [207] Course Schedule
#
# @lc code=start
# TAGS: Breath First Search, Depth First Search, Graph, Topological Sort
# REVIEWME:
class Solution:
# 104 ms, 64.59%. First attempt. Not a clean solution
# Time and Space: O(N + E)
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = collections.defaultdict(list)
for course, pre in prerequisites:
graph[course].append(pre)
visited = [0]*numCourses
self.ans = True
def dfs(n):
if visited[n] == 1:
return
if visited[n] == -1:
self.ans = False
return
visited[n] = -1
for i in graph[n]:
dfs(i)
visited[n] = 1
for i in range(numCourses):
dfs(i)
return self.ans
# 100 ms, 80.36%. Same complexity. Cleaner solution
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = collections.defaultdict(list)
for course, pre in prerequisites:
graph[course].append(pre)
visited = [0]*numCourses
def dfs(n):
if visited[n] == 1:
return True
if visited[n] == -1:
return False
visited[n] = -1
for i in graph[n]:
if not dfs(i):
return False
visited[n] = 1
return True
return all(dfs(i) for i in range(numCourses))
# @lc code=end