-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse Schedule.java
35 lines (30 loc) · 1.03 KB
/
Course Schedule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
int[] colors;
boolean res = true;
public boolean canFinish(int numCourses, int[][] prerequisites) {
// DFS check if it's DAG
// 0, 1, 2 --> white, gray, black
colors = new int[numCourses];
List<List<Integer>> graph = new ArrayList<>();
for(int i = 0; i < numCourses; i++) graph.add(new ArrayList<>());
for(int[] prereq: prerequisites) {
// add child
graph.get(prereq[1]).add(prereq[0]);
}
for(int i = 0; i < numCourses; i++) {
if(colors[i] == 0) dfs(graph, i);
}
return res;
}
private void dfs(List<List<Integer>> graph, int i) {
colors[i] = 1;
List<Integer> list = graph.get(i);
if(list != null) {
for(int next: list) {
if(colors[next] == 1) res = false;
else if(colors[next] == 0) dfs(graph, next);
}
}
colors[i] = 2;
}
}