class Solution {
boolean[] onPath;
boolean[] visited;
boolean hasCycle = false;
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] graph = buildGraph(numCourses, prerequisites);
onPath = new boolean[numCourses];
visited = new boolean[numCourses];
for (int i = 0; i < numCourses; i++) {
traverse(graph, i);
}
return !hasCycle;
}
void traverse(List<Integer>[] graph, int s) {
if (hasCycle) {
return;
}
if (onPath[s]) {
hasCycle = true;
return;
}
if (visited[s]) {
return;
}
visited[s] = true;
onPath[s] = true;
for (int t : graph[s]) {
traverse(graph, t);
}
onPath[s] = false;
visited[s] = false;
}
List<Integer>[] buildGraph(int numCourses, int[][] prerequisites) {
List<Integer>[] graph = new LinkedList[numCourses];
for (int i = 0; i < numCourses; i++) {
graph[i] = new LinkedList<>();
}
for (int[] edge: prerequisites) {
graph[edge[0]].add(edge[1]);
}
return graph;
}
}