207. Course Schedule#

 1class Solution {
 2
 3  public boolean canFinish(int numCourses, int[][] prerequisites) {
 4    ArrayList<Integer>[] adjList = new ArrayList[numCourses];
 5
 6    for (int i = 0; i < numCourses; ++i) {
 7      adjList[i] = new ArrayList<>();
 8    }
 9
10    for (int[] prereq : prerequisites) {
11      adjList[prereq[1]].add(prereq[0]);
12    }
13
14    boolean[] visited = new boolean[numCourses];
15    boolean[] completed = new boolean[numCourses];
16
17    for (int i = 0; i < numCourses; ++i) {
18      if (hasCycle(i, adjList, visited, completed)) {
19        return false;
20      }
21    }
22
23    return true;
24  }
25
26  private boolean hasCycle(
27    int i,
28    List<Integer>[] adjList,
29    boolean[] visited,
30    boolean[] completed
31  ) {
32    if (completed[i]) return false;
33
34    visited[i] = true;
35    for (int n : adjList[i]) {
36      if (visited[n] || hasCycle(n, adjList, visited, completed)) {
37        return true;
38      }
39    }
40    visited[i] = false;
41    completed[i] = true;
42
43    return false;
44  }
45}