-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCourse Schedule II
58 lines (47 loc) · 1.54 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
56
57
58
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
int[] answer=new int[numCourses];
int k=0;
for(int i=0;i<numCourses;i++){
graph.add(new ArrayList<Integer>());
}
for(int i=0;i<prerequisites.length;i++){
int u=prerequisites[i][0];
int v=prerequisites[i][1];
graph.get(v).add(u);
}
// kahn's algo
Queue<Integer> q=new LinkedList<>();
int[] indegree = new int[numCourses];
boolean[] visited = new boolean[numCourses];
for(int i=0;i<numCourses;i++){
for(int neighbour:graph.get(i)){
indegree[neighbour]+=1;
}
}
for(int i=0;i<numCourses;i++){
if(indegree[i]==0){
q.add(i);
}
}
while(!q.isEmpty()){
int currentVertex = q.remove();
if(visited[currentVertex]==true)
continue;
visited[currentVertex]=true;
answer[k]=currentVertex;
k++;
for(int neighbour:graph.get(currentVertex)){
indegree[neighbour]-=1;
if(indegree[neighbour]==0){
q.add(neighbour);
}
}
}
if(k!=numCourses){
return new int[0];
}
return answer;
}
}