-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207.CourseSchedule.java
More file actions
50 lines (44 loc) · 1.55 KB
/
Copy path207.CourseSchedule.java
File metadata and controls
50 lines (44 loc) · 1.55 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
//Time Complexity = O(5N) ~ O(N)
//Space Complexity = O(N) hashmap + O(N) degree array
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
HashMap<Integer,List<Integer>> map = new HashMap<>();
List<Integer> li = new ArrayList<>();
//Initialize Arraylists in each key of HashMap
for(int i =0 ; i<numCourses;i++){
map.put(i,new ArrayList<Integer>());
}
int[] degree = new int[numCourses];
//update degree array and hashMap
for(int[] preReq : prerequisites){
degree[preReq[0]] += 1;
li = map.get(preReq[1]);
li.add(preReq[0]);
map.put(preReq[1],li);
}
Queue<Integer> q = new LinkedList<>();
//add initial independent courses to queue
for(int i=0; i< numCourses; i++){
if(degree[i]==0)q.add(i);
}
//base
if(q.size() == 0) return false;
while(!q.isEmpty()){
//remove one element
int curr = q.poll();
li = map.get(curr);
//process the element- get arraylist from map and decrease its degree in degree array
for(int course: li){
degree[course] -= 1;
//if it's 0 then add it to queue
if(degree[course] == 0)q.add(course);
}
map.remove(curr);
}
//if any valuein degree array != 0 return false
for(int course: degree){
if(course != 0) return false;
}
return true;
}
}