-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCourseSchedule2.java
More file actions
65 lines (59 loc) · 1.67 KB
/
Copy pathCourseSchedule2.java
File metadata and controls
65 lines (59 loc) · 1.67 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class CourseSchedule2 {
HashSet<Integer> visited = new HashSet<Integer>();
HashSet<Integer> sorted = new HashSet<Integer>();
HashMap<Integer,ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>();
int[] arr;
int pointer;
// topological sort
// it's ok to be in the sorted list
// but in dfs the node can't be visited before
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] empty = {};
for (int[] pre:prerequisites){
if(!map.containsKey(pre[0])){
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(pre[1]);
map.put(pre[0], a);
}
else
map.get(pre[0]).add(pre[1]);
}
arr = new int[numCourses];
pointer = 0;
for(int i = 0; i< numCourses; i++){
if (!this.dfs(i))
return empty;
}
if(pointer == numCourses)
return arr;
else
return empty;
}
private boolean dfs(int course){
if(sorted.contains(course))
return true;
else if(visited.contains(course))
return false;
this.visited.add(course);
if(map.containsKey(course))
for(int pre:map.get(course)){
if(!this.dfs(pre))
return false;
}
arr[pointer++] = course;
sorted.add(course);
this.visited.remove(course);
return true;
}
public static void main(String args[]){
CourseSchedule2 cs2 = new CourseSchedule2();
int[][] arr = {{1,0},{2,0},{3,1},{3,2}};
for(int course: cs2.findOrder(4,arr)){
System.out.printf("%d\n",course);
}
}
}