-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCourse Schedule II
55 lines (51 loc) · 1.44 KB
/
Course Schedule II
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
48
49
50
51
52
53
54
55
class Solution {
int[] res;
int resIdx = 0;
boolean[] visited;
List<List<Integer>> adjacencyList;
public int[] findOrder(int numCourses, int[][] prerequisites) {
res = new int[numCourses];
visited = new boolean[numCourses];
adjacencyList = createAdjacencyList(numCourses, prerequisites);
Stack<Integer> visitesInDfs = new Stack<>();
for (int i = 0; i < numCourses; i++) {
if (!dfs(i, visitesInDfs)) {
int[] tmpRes = {};
return tmpRes;
}
}
return res;
}
public boolean dfs(int currCourseNum, Stack<Integer> visitesInDfs) {
if (visitesInDfs.contains(currCourseNum)) {
return false;
}
if (visited[currCourseNum]) {
return true;
}
visited[currCourseNum] = true;
visitesInDfs.add(currCourseNum);
List<Integer> currCourseWithPreq = adjacencyList.get(currCourseNum);
for (int preq : currCourseWithPreq) {
if (!dfs(preq, visitesInDfs)) {
return false;
}
}
res[resIdx++] = currCourseNum;
visitesInDfs.pop();
return true;
}
public List<List<Integer>> createAdjacencyList(int numCourses, int[][] prerequisites) {
List<List<Integer>> adjacencyList = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
adjacencyList.add(new ArrayList<>());
}
for (int[] coursePreqArr : prerequisites) {
List<Integer> coursePreqList = adjacencyList.get(coursePreqArr[0]);
for (int i = 1; i < coursePreqArr.length; i++) {
coursePreqList.add(coursePreqArr[i]);
}
}
return adjacencyList;
}
}