-
Notifications
You must be signed in to change notification settings - Fork 0
/
CourseSchedule.java
39 lines (35 loc) · 1.14 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
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < prerequisites.length; i++) {
adj.get(prerequisites[i][0]).add(prerequisites[i][1]);
}
int[] visited = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
if (visited[i] == 0) {
if (isCyclic(adj, visited, i)) {
return false;
}
}
}
return true;
}
private boolean isCyclic(List<List<Integer>> adj, int[] visited, int curr) {
if (visited[curr] == 2) {
return true;
}
visited[curr] = 2;
for (int i = 0; i < adj.get(curr).size(); i++) {
if (visited[adj.get(curr).get(i)] != 1) {
if (isCyclic(adj, visited, adj.get(curr).get(i))) {
return true;
}
}
}
visited[curr] = 1;
return false;
}
}