-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse Schedule
48 lines (40 loc) · 1.31 KB
/
Course Schedule
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
public 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;
}
// counter for number of prerequisites
int[] pCounter = new int[numCourses];
for(int i=0; i<len; i++){
pCounter[prerequisites[i][0]]++;
}
//store courses that have no prerequisites
LinkedList<Integer> queue = new LinkedList<Integer>();
for(int i=0; i<numCourses; i++){
if(pCounter[i]==0){
queue.add(i);
}
}
// number of courses that have no prerequisites
int numNoPre = queue.size();
while(!queue.isEmpty()){
int top = queue.remove();
for(int i=0; i<len; i++){
// if a course's prerequisite can be satisfied by a course in queue
if(prerequisites[i][1]==top){
pCounter[prerequisites[i][0]]--;
if(pCounter[prerequisites[i][0]]==0){
numNoPre++;
queue.add(prerequisites[i][0]);
}
}
}
}
return numNoPre == numCourses;
}
}
http://www.programcreek.com/2014/05/leetcode-course-schedule-java/