Course Schedule in Python

PythonServer Side ProgrammingProgramming

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(Python)

Let us see the following implementation to get better understanding −

class Solution(object):
   def canFinish(self, numCourses, prerequisites):
      """
      :type numCourses: int
      :type prerequisites: List[List[int]]
      :rtype: bool
      """
      if len(prerequisites) == 0:
         return True
      visited = [0 for i in range(numCourses)]
      adj_list = self.make_graph(prerequisites)
      print(adj_list)
      for i in range(numCourses):
         if not visited[i]:
            if not self.cycle(adj_list,visited,i):
               return False
      return True
   def cycle(self,adj_list,visited,current_node = 0):
      if visited[current_node] ==-1:
         return False
      if visited[current_node] == 1:
         return True
      visited[current_node] = -1
      if(current_node in adj_list):
         for i in adj_list[current_node]:
            if not self.cycle(adj_list,visited,i):
               return False
      visited[current_node] = 1
      return True
   def make_graph(self,array):
      adj_list = {}
      for i in array:
         if i[1] in adj_list:
            adj_list[i[1]].append(i[0])
         else:
            adj_list[i[1]] = [i[0]]
      return adj_list

Input

2
[[1,0]]

Output

true
raja
Published on 17-Mar-2020 05:46:36
Advertisements