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

Suppose we have a 2D matrix where matrix[i] represents the list of prerequisite courses needed to enroll in course i. We need to check whether it is possible to take all courses without encountering circular dependencies.

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.

Algorithm Overview

This problem is essentially detecting cycles in a directed graph. We use Depth-First Search (DFS) with two tracking arrays:

  • vis − tracks nodes currently in the DFS path (cycle detection)

  • chk − tracks nodes that have been completely processed

Step-by-Step Approach

To solve this, we follow these steps −

  • Define a function dfs(i) that takes course index i

  • If vis[i] is true, return False (cycle detected)

  • If chk[i] is true, return True (already processed)

  • Mark vis[i] = True (enter DFS path)

  • For each prerequisite j in matrix[i], recursively call dfs(j)

  • Mark vis[i] = False (exit DFS path)

  • Mark chk[i] = True (mark as processed)

  • Return True

Example

class Solution:
    def solve(self, matrix):
        vis = [False for _ in matrix]
        chk = [False for _ in matrix]
        
        def dfs(i):
            if vis[i]: 
                return False  # Cycle detected
            if chk[i]: 
                return True   # Already processed
            
            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

# Test the solution
ob = Solution()
matrix = [[1], [2], []]
print(ob.solve(matrix))
True

How It Works

Let's trace through the example matrix = [[1], [2], []] ?

  • Course 0 requires course 1

  • Course 1 requires course 2

  • Course 2 has no prerequisites

The algorithm processes each course and verifies no circular dependencies exist. The valid order would be: Course 2 ? Course 1 ? Course 0.

Another Example with Cycle

# Example with circular dependency
ob = Solution()
matrix_with_cycle = [[1], [0]]  # Course 0 needs 1, Course 1 needs 0
print("Can take all courses:", ob.solve(matrix_with_cycle))
Can take all courses: False

Time and Space Complexity

  • Time Complexity: O(V + E) where V is number of courses and E is total prerequisites

  • Space Complexity: O(V) for the visited and checked arrays

Conclusion

This solution uses DFS with cycle detection to determine if all courses can be completed. The key insight is treating prerequisites as a directed graph and checking for cycles using two tracking arrays.

Updated on: 2026-03-25T10:59:05+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements