-
Notifications
You must be signed in to change notification settings - Fork 0
/
29. Course_Schedule.java
49 lines (45 loc) · 1.42 KB
/
29. Course_Schedule.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
46
47
48
49
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if(prerequisites == null){
throw new IllegalArgumentException("illegal prerequisites array");
}
int len = prerequisites.length;
if(numCourses == 0 || len == 0){
return true;
}
//track visited courses
int[] visit = new int[numCourses];
// use the map to store what courses depend on a course
HashMap<Integer,ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>();
for(int[] a: prerequisites){
if(map.containsKey(a[1])){
map.get(a[1]).add(a[0]);
}
else{
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(a[0]);
map.put(a[1], l);
}
}
for(int i=0; i<numCourses; i++){
if(!canFinishDFS(map, visit, i))
return false;
}
return true;
}
private boolean canFinishDFS(HashMap<Integer,ArrayList<Integer>> map, int[] visit, int i){
if(visit[i]==-1)
return false;
if(visit[i]==1)
return true;
visit[i]=-1;
if(map.containsKey(i)){
for(int j: map.get(i)){
if(!canFinishDFS(map, visit, j))
return false;
}
}
visit[i]=1;
return true;
}
}