Program to check whether we can take all courses or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a 2D matrix where matrix[i] represents the list of prerequisite courses needed to enroll course i. Now, we have to check whether it is possible to take all courses or not.

So, if the input is like matrix = [[1],[2],[]], then the output will be True, as we can take course 2, then course 1, and then course 0.

To solve this, we will follow these steps −

  • Define a function dfs(). This will take i

  • if vis[i] is true, then

    • return false

  • if chk[i] is true, then

    • return True

  • vis[i]:= True

  • for each j in matrix[i], do

    • if dfs(j) is false, then

      • return False

  • vis[i]:= False

  • chk[i]:= True

  • return True

  • From the main method, do the following −

  • vis:= a list of size same as row count of matrix and initially all are false

  • chk:= a list of size same as row count of matrix and initially all are false

  • for i in range 0 to row count of matrix, do

    • if dfs(i) is false, then

      • return False

  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, matrix):
      vis=[False for _ in matrix]
      chk=[False for _ in matrix]
      def dfs(i):
         if vis[i]: return False
         if chk[i]: return True
         vis[i]=True
         for j in matrix[i]:
            if not dfs(j):
               return False
         vis[i]=False
         chk[i]=True
         return True
   for i in range(len(matrix)):
      if not dfs(i):
         return False
   return True
ob = Solution()
matrix = [ [1], [2], [] ]
print(ob.solve(matrix))

Input

matrix = [
   [1],
   [2],
   []
]

Output

True
raja
Published on 07-Oct-2020 10:57:36
Advertisements