Course Schedule II in Python

PythonServer Side ProgrammingProgramming

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

Let us see the following implementation to get better understanding −

class Solution(object):
   def findOrder(self, numCourses, prerequisites):
      in_degree,adj=self.create_adj(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]
   def create_adj(self,n,graph):
      adj = {}
      in_degree= [0 for i in range(n)]
      for i in graph:
         in_degree[i[0]]+=1
         if i[1] in adj:
            adj[i[1]].append(i[0])
         else:
            adj[i[1]] = [i[0]]
      return in_degree,adj
   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]:
            if not self.dfs(i,visited,stack,adj):
               return False
      visited[node]=1
      stack.append(node)
      return True

Input

2
[[1,0]]

Output

[0,1]
raja
Published on 17-Mar-2020 05:50:43
Advertisements