Skip to content

Commit 800bfb4

Browse files
authored
Create Course Schedule II - Leetcode 210.py
1 parent 3a87264 commit 800bfb4

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
3+
order = []
4+
g = defaultdict(list)
5+
for a, b in prerequisites:
6+
g[a].append(b)
7+
8+
UNVISITED, VISITING, VISITED = 0, 1, 2
9+
states = [UNVISITED] * numCourses
10+
11+
12+
def dfs(i):
13+
if states[i] == VISITING:
14+
return False
15+
elif states[i] == VISITED:
16+
return True
17+
states[i] = VISITING
18+
19+
for nei in g[i]:
20+
if not dfs(nei):
21+
return False
22+
23+
states[i] = VISITED
24+
order.append(i)
25+
return True
26+
27+
28+
for i in range(numCourses):
29+
if not dfs(i):
30+
return []
31+
32+
return order # Time: O(V + E), Space: O(V + E)
33+

0 commit comments

Comments
 (0)