Problem statement

https://binarysearch.com/problems/Course-Scheduling/

Solution

Equal to Leetcode 0207. Course Schedule.

Complexity

Time and space is O(E + V).

Code

class Solution:
    def solve(self, courses):
        def dfs(start):
            if self.FoundCycle == 1: return
            if self.V[start] == 1:
                self.FoundCycle = 1
            if self.V[start] == 0:
                self.V[start] = 1
                for neib in courses[start]:
                    dfs(neib)
                self.V[start] = 2

        n = len(courses)

        self.V = [0] * n
        self.FoundCycle = 0

        for i in range(n):
            if self.FoundCycle == 1: break
            if self.V[i] == 0:
                dfs(i)

        return self.FoundCycle == 0