Skip to content

Commit

Permalink
Update 0210-course-schedule-ii.py
Browse files Browse the repository at this point in the history
  • Loading branch information
raghadala committed Jul 6, 2024
1 parent 406b3e0 commit 82572b7
Showing 1 changed file with 31 additions and 25 deletions.
56 changes: 31 additions & 25 deletions 11_Graphs/09_Course_Schedule_II/0210-course-schedule-ii.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,34 @@

class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = {i: [] for i in range(numCourses)}
in_degree = [0] * numCourses
order = []

# Construct the graph and count in-degrees
for course, prereq in prerequisites:
graph[prereq].append(course)
in_degree[course] += 1

# Initialize a queue with nodes having in-degree zero
queue = collections.deque(
[course for course, degree in enumerate(in_degree) if degree == 0]
)

# Perform topological sorting and update in-degrees
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)

# If the order doesn't contain all courses, there's a cycle
return order if len(order) == numCourses else []
preReq = defaultdict(list)
#build graph
for course,p in prerequisites:
preReq[course].append(p)

res = []
visited, cycle = set(), set()

def dfs(course):
# terminating case
if course in cycle:
return False

if course in visited:
return True
else:
cycle.add(course)

for p in preReq[c]:
if not dfs(p):
return False
cycle.remove(course). #after processing add to visited
visited.add(course)
res.append(course)
return True

for c in range(numCourses):
if dfs(c) == False:
return []

return res

0 comments on commit 82572b7

Please sign in to comment.