-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourseScheduleII.py
More file actions
28 lines (22 loc) · 828 Bytes
/
Copy pathcourseScheduleII.py
File metadata and controls
28 lines (22 loc) · 828 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
from collections import defaultdict
class Solution:
def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:
graph = defaultdict(list)
for a, b in prerequisites:
graph[a].append(b)
def has_cycle(node, history, result):
if history[node] == 1: return True
if history[node] == 2: return False
history[node] = 1
for child in graph[node]:
if has_cycle(child, history, result):
return True
result.append(node)
history[node] = 2
return False
history = [0] * numCourses
result = []
for i in range(numCourses):
if has_cycle(i, history, result):
return []
return result