-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourseSchedule.java
45 lines (36 loc) · 1.12 KB
/
CourseSchedule.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
36
37
38
39
40
41
42
43
44
45
import java.util.ArrayList;
import java.util.List;
public class CourseSchedule {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : prerequisites) {
graph.get(edge[1]).add(edge[0]);
}
int[] visited = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
if (visited[i] == 0 && !dfs(graph, visited, i)) {
return false;
}
}
return true;
}
private boolean dfs(List<List<Integer>> graph, int[] visited, int course) {
if (visited[course] == 1) {
return false;
}
if (visited[course] == 2) {
return true;
}
visited[course] = 1;
for (int next : graph.get(course)) {
if (!dfs(graph, visited, next)) {
return false;
}
}
visited[course] = 2;
return true;
}
}