-
Notifications
You must be signed in to change notification settings - Fork 33
/
Course_Schedule_II.java
43 lines (36 loc) · 1.41 KB
/
Course_Schedule_II.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
//Leetcode 210. Course Schedule II
//Question - https://leetcode.com/problems/course-schedule-ii/
//Kahn's Topological Sort
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int result[] = new int[numCourses];
int cntVertex = 0;
Queue<Integer> inDegree0 = new LinkedList<>();
int inDegree[] = new int[numCourses];
Arrays.fill(inDegree,0);
for(int i=0 ; i<prerequisites.length ; i++){
inDegree[prerequisites[i][0]]++;
}
for(int i=0 ; i<numCourses ; i++){
if(inDegree[i]==0) inDegree0.add(i);
}
while(!inDegree0.isEmpty()){
int curr = inDegree0.poll();
ArrayList<Integer> neighbours = findNeighbours(prerequisites,curr);
result[cntVertex] = curr;
for(int neighbour : neighbours){
if(--inDegree[neighbour]==0) inDegree0.add(neighbour);
}
cntVertex++;
}
if(cntVertex!=numCourses) return (new int[0]);
else return result;
}
public ArrayList<Integer> findNeighbours(int[][] prerequisites, int v){
ArrayList<Integer> neighbours = new ArrayList<Integer>();
for(int i=0;i<prerequisites.length;i++){
if(prerequisites[i][1]==v) neighbours.add(prerequisites[i][0]);
}
return neighbours;
}
}