## Course Schedule

• Time:O(|V| + |E|), where |V| = \texttt{numCourses} and |E| = |\texttt{prerequisites}|
• Space:O(|V| + |E|), where |V| = \texttt{numCourses} and |E| = |\texttt{prerequisites}|

## C++

enum class State { INIT, VISITING, VISITED };

class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
vector<State> state(numCourses);

for (const auto& p : prerequisites)
graph[p[1]].push_back(p[0]);

for (int i = 0; i < numCourses; ++i)
if (hasCycle(graph, i, state))
return false;

return true;
}

private:
bool hasCycle(const vector<vector<int>>& graph, int u, vector<State>& state) {
if (state[u] == State::VISITING)
return true;
if (state[u] == State::VISITED)
return false;

state[u] = State::VISITING;
for (const int v : graph[u])
if (hasCycle(graph, v, state))
return true;
state[u] = State::VISITED;

return false;
}
};

## JAVA

enum State { INIT, VISITING, VISITED }

class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] graph = new List[numCourses];
State[] state = new State[numCourses];

for (int i = 0; i < numCourses; ++i)
graph[i] = new ArrayList<>();

for (int[] p : prerequisites)

for (int i = 0; i < numCourses; ++i)
if (hasCycle(graph, i, state))
return false;

return true;
}

private boolean hasCycle(List<Integer>[] graph, int u, State[] state) {
if (state[u] == State.VISITING)
return true;
if (state[u] == State.VISITED)
return false;

state[u] = State.VISITING;
for (final int v : graph[u])
if (hasCycle(graph, v, state))
return true;
state[u] = State.VISITED;

return false;
}
}

## Python

from enum import Enum

class State(Enum):
INIT = 0
VISITING = 1
VISITED = 2

class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = [[] for _ in range(numCourses)]
state = [State.INIT] * numCourses

for a, b in prerequisites:
graph[b].append(a)

def hasCycle(u: int) -> bool:
if state[u] == State.VISITING:
return True
if state[u] == State.VISITED:
return False

state[u] = State.VISITING
if any(hasCycle(v) for v in graph[u]):
return True
state[u] = State.VISITED

return False

return not any(hasCycle(i) for i in range(numCourses))