-
Notifications
You must be signed in to change notification settings - Fork 14
/
210-course-schedule-ii.py
64 lines (54 loc) · 1.84 KB
/
210-course-schedule-ii.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
62
63
64
from collections import deque
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = [[] for _ in range(numCourses)]
indegrees = [0 for _ in range(numCourses)]
for q, p in prerequisites:
graph[p].append(q)
indegrees[q] += 1
queue = deque([])
for i, indegree in enumerate(indegrees):
if indegree == 0:
queue.append(i)
res = []
while queue:
node = queue.popleft()
res.append(node)
for neighbor in graph[node]:
indegrees[neighbor] -= 1
if indegrees[neighbor] == 0:
queue.append(neighbor)
return res if len(res) == numCourses else []
# time O(V+E)
# space O(V+E), due to building graph
# using graph and kahn and topological sort
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = [[] for _ in range(numCourses)]
for q, p in prerequisites:
graph[p].append(q)
node_flag = [0 for _ in range(numCourses)]
cyclic = False
res = []
def dfs(node):
nonlocal cyclic
node_flag[node] = 1
for neighbor in graph[node]:
if node_flag[neighbor] == 0:
dfs(neighbor)
elif node_flag[neighbor] == 1:
cyclic = True
node_flag[node] = 2
res.append(node)
for node in range(numCourses):
if node_flag[node] == 0:
dfs(node)
return res[::- 1] if not cyclic else []
# time O(V+E)
# space O(V+E)
# using graph and dfs and detecting cycles
'''
# 0 not visited
# 1 visiting
# 2 completed visited
'''