# Course Schedule in Python

Suppose there are a total of numCourses courses we have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 we have to first take course 1, which is expressed using a pair: [0,1]. Suppose there are total number of courses that is provided and a list of prerequisite pairs, we have to check whether is it possible for you to finish all courses?

So if the input is like − numCourses = 2 and prerequisites = [[1, 0]], then the result will be true, because there are a total of 2 courses to take. To take course 1 we should have finished course 0. So it is possible.

To solve this, we will follow these steps −

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

• if prerequisites has no entry, then return true

• make an array called visited, fill this with 0, and its range is same as numCourses

• adj_list := create a graph using prerequisites

• for i in range 0 to numCourses

• if visited[i] is false, then

• if there is no cycle among the visited node in the graph, return false

• return true

## Example

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

Live Demo

class Solution(object):
def canFinish(self, numCourses, prerequisites):
if len(prerequisites) == 0:
return True
visited = [0 for i in range(numCourses)]
for i in range(numCourses):
if not visited[i]:
return False
return True
if visited[current_node] ==-1:
return False
if visited[current_node] == 1:
return True
visited[current_node] = -1
return False
visited[current_node] = 1
return True
def make_graph(self,array):
for i in array:
else:
ob = Solution()
print(ob.canFinish(2, [[1,0]]))

## Input

2
[[1,0]]

## Output

true

Updated on: 29-Apr-2020

618 Views

Get certified by completing the course