forked from dimitar9/Algorithm_Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT210_course_2.java
More file actions
47 lines (44 loc) · 1.3 KB
/
T210_course_2.java
File metadata and controls
47 lines (44 loc) · 1.3 KB
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
46
47
public class Solution {
private int N = 0;
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] result = new int[numCourses];
Course[] courses = new Course[numCourses];
for (int i = 0; i < numCourses; i++) {
courses[i] = new Course(i);
}
for (int i = 0; i < prerequisites.length; i++) {
courses[prerequisites[i][0]].add(courses[prerequisites[i][1]]);
}
for (int i = 0; i < numCourses; i++) {
if (isCyclic(courses[i], result)) {
return new int[0];
}
}
return result;
}
private boolean isCyclic(Course cur, int[] result) {
if (cur.tested == true) return false;
if (cur.visited == true) return true;
cur.visited = true;
for (Course c : cur.pre) {
if (isCyclic(c, result)) {
return true;
}
}
cur.tested = true;
result[N++] = cur.number;
return false;
}
class Course {
boolean visited = false;
boolean tested = false;
int number;
List<Course> pre = new ArrayList<Course>();
public Course(int i) {
number = i;
}
public void add(Course c) {
pre.add(c);
}
}
}