# Course Schedule II in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose there are a total of n courses, these are labeled from 0 to n-1. Some courses may have prerequisites, given the total number of courses and a list of prerequisite pairs, we have to find the ordering of courses that we should take to finish all courses. There may be multiple correct orders, we just need to find one of them. If it is impossible to finish all courses, then return an empty array.

So if the input is like 2, [[1, 0]], then the result will be [0,1]. There are a total of 2 courses to take. To take course number 1 we should have finished course 0. So the correct course order is [0,1]

To solve this, we will follow these steps −

• In the main method, it will take numCourses, and prerequisites: This will act like −

• Define an array called in_degree, and fill with all in degrees of all nodes, and adj := adjacency list of the graph

• Define one array called visited, and fill this with 0, its size is same as numCourses

• Define one empty stack.

• for i in range 0 to numCourses

• if visited[i] is false and dfs of node i is false by passing the stack into it, then

• return an empty list

• return the stack elements in reverse order.

## Example

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def findOrder(self, numCourses, prerequisites):
visited = [0 for i in range(numCourses)]
stack = []
for i in range(numCourses):
if not visited[i] and not self.dfs(i,visited,stack,adj):
return []
return stack[::-1]
in_degree= [0 for i in range(n)]
for i in graph:
in_degree[i]+=1
if i in adj:
else:
def dfs(self, node, visited,stack,adj):
if visited[node] == -1:
return False
if visited[node] == 1:
return True
visited[node] = -1
if node in adj:
for i in adj[node]:
return False
visited[node]=1
stack.append(node)
return True
ob = Solution()
print(ob.findOrder(2, [[1,0]]))

## Input

2
[[1,0]]

## Output

[0,1]