File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ /*
3
+ Same as course schedule, as an when we are done exploring for a node i.e when we insert the element in queue, when
4
+ we pop out, we add it to the result array.
5
+ */
6
+ public int [] findOrder (int numCourses , int [][] prerequisites ) {
7
+ int [] inDegree = new int [numCourses ];
8
+ int [] res = new int [numCourses ];
9
+ for (int i =0 ; i < prerequisites .length ;i ++) {
10
+ inDegree [prerequisites [i ][0 ]]++;
11
+ }
12
+
13
+ Queue <Integer > q = new LinkedList <>();
14
+ for (int j =0 ; j <inDegree .length ; j ++) {
15
+ if (inDegree [j ] == 0 ) {
16
+ q .offer (j );
17
+ }
18
+ }
19
+ int k = 0 ;
20
+ while (!q .isEmpty ()) {
21
+ int out = q .poll ();
22
+ res [k ] = out ;
23
+ k ++;
24
+ for (int i =0 ; i <prerequisites .length ; i ++) {
25
+ if (prerequisites [i ][1 ] == out ) {
26
+ inDegree [prerequisites [i ][0 ]]--;
27
+ if (inDegree [prerequisites [i ][0 ]] == 0 ) {
28
+ q .offer (prerequisites [i ][0 ]);
29
+ }
30
+ }
31
+ }
32
+
33
+ }
34
+ return numCourses == k ? res : new int []{};
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments