-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcourse-schedule.py
61 lines (54 loc) · 1.63 KB
/
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
58
59
60
61
# Time: O(|V| + |E|)
# Space: O(|E|)
import collections
# Khan's algorithm (bfs solution)
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
adj = collections.defaultdict(list)
in_degree = collections.Counter()
for u, v in prerequisites:
in_degree[u] += 1
adj[v].append(u)
result = []
q = [u for u in xrange(numCourses) if u not in in_degree]
while q:
new_q = []
for u in q:
result.append(u)
for v in adj[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
new_q.append(v)
q = new_q
return len(result) == numCourses
# Time: O(|V| + |E|)
# Space: O(|E|)
import collections
# dfs solution
class Solution2(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
adj = collections.defaultdict(list)
in_degree = collections.Counter()
for u, v in prerequisites:
in_degree[u] += 1
adj[v].append(u)
result = []
stk = [u for u in xrange(numCourses) if u not in in_degree]
while stk:
u = stk.pop()
result.append(u)
for v in adj[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
stk.append(v)
return len(result) == numCourses