Skip to content

Commit 0b04dac

Browse files
committed
update
1 parent b33505e commit 0b04dac

File tree

2 files changed

+38
-4
lines changed

2 files changed

+38
-4
lines changed

[K]graph/[K]graph-kahn/207-course-schedule.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
2020
indegrees[neighbor] -= 1
2121
if indegrees[neighbor] == 0:
2222
queue.append(neighbor)
23+
2324
return len(res) == numCourses
2425

2526
# time O(V+E)
@@ -38,9 +39,6 @@ def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
3839
def dfs(node):
3940
nonlocal cyclic
4041
node_flag[node] = 1
41-
if not graph[node]:
42-
node_flag[node] = 2
43-
return
4442
for neighbor in graph[node]:
4543
if node_flag[neighbor] == 0:
4644
dfs(neighbor)

[K]graph/[K]graph-kahn/210-course-schedule-ii.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,40 @@ def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int
2525

2626
# time O(V+E)
2727
# space O(V+E), due to building graph
28-
# using graph and kahn and topological sort
28+
# using graph and kahn and topological sort
29+
30+
class Solution:
31+
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
32+
graph = [[] for _ in range(numCourses)]
33+
for q, p in prerequisites:
34+
graph[p].append(q)
35+
36+
node_flag = [0 for _ in range(numCourses)]
37+
cyclic = False
38+
res = []
39+
40+
def dfs(node):
41+
nonlocal cyclic
42+
node_flag[node] = 1
43+
for neighbor in graph[node]:
44+
if node_flag[neighbor] == 0:
45+
dfs(neighbor)
46+
elif node_flag[neighbor] == 1:
47+
cyclic = True
48+
node_flag[node] = 2
49+
res.append(node)
50+
51+
for node in range(numCourses):
52+
if node_flag[node] == 0:
53+
dfs(node)
54+
55+
return res[::- 1] if not cyclic else []
56+
57+
# time O(V+E)
58+
# space O(V+E)
59+
# using graph and dfs and detecting cycles
60+
'''
61+
# 0 not visited
62+
# 1 visiting
63+
# 2 completed visited
64+
'''

0 commit comments

Comments
 (0)