-
Notifications
You must be signed in to change notification settings - Fork 0
/
0210__course_schedule_2.py
57 lines (44 loc) · 1.51 KB
/
0210__course_schedule_2.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
"""
LeetCode: https://leetcode.com/problems/course-schedule-ii/
"""
from collections import defaultdict
from typing import List, Dict, Set
from unittest import TestCase
class Solution(TestCase):
def test_example_1(self):
self.assertEqual([0, 1], self.findOrder(2, [[1, 0]]))
def test_example_2(self):
self.assertTrue(
self.findOrder(4, [[1, 0], [2, 0], [3, 1], [3, 2]]) in [
[0, 2, 1, 3],
[0, 1, 2, 3]
]
)
def test_example_3(self):
self.assertEqual([0], self.findOrder(1, []))
def test_case_40(self):
self.assertEqual([2, 1, 0], self.findOrder(3, [[0, 1], [0, 2], [1, 2]]))
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
adj: Dict[int, Set[int]] = defaultdict(set)
for src, dst in prerequisites:
adj[src].add(dst)
visited: Set[int] = set()
cycle: Set[int] = set()
result: List[int] = []
def dfs(course: int) -> bool:
if course in visited:
return True
if course in cycle:
return False
cycle.add(course)
for nei in adj[course]:
if not dfs(nei):
return False
visited.add(course)
result.append(course)
return True
for n in range(numCourses):
cycle.clear()
if n not in visited and not dfs(n):
return []
return result