File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean canFinish (int numCourses , int [][] prerequisites ) {
3
+ /*
4
+ This is a dependency type question because inorder to complete a course, we need to complete it's
5
+ pre-requistes, hence we can apply topological sort here.
6
+ We can initialize an array with index representing the courses and the value representing the number
7
+ of pre-requistes to complete that particular course essentially representing a graph with nodes
8
+ directing inside it as the pre-requistes. We then apply BFS and if there are no-prerequistes left
9
+ we add it to queue. In the end, we check if the inDegree array is empty or not. If it is not empty,
10
+ that means it course cannot be finished.
11
+ T.C. - O(V+E), Space - O(V)
12
+ */
13
+
14
+ int [] inDegree = new int [numCourses ];
15
+
16
+ for (int i =0 ; i < prerequisites .length ;i ++) {
17
+ inDegree [prerequisites [i ][0 ]]++;
18
+ }
19
+
20
+ Queue <Integer > q = new LinkedList <>();
21
+ for (int j =0 ; j <inDegree .length ; j ++) {
22
+ if (inDegree [j ] == 0 ) {
23
+ q .offer (j );
24
+ }
25
+ }
26
+ while (!q .isEmpty ()) {
27
+ int out = q .poll ();
28
+ for (int i =0 ; i <prerequisites .length ; i ++) {
29
+ if (prerequisites [i ][1 ] == out ) {
30
+ inDegree [prerequisites [i ][0 ]]--;
31
+ if (inDegree [prerequisites [i ][0 ]] == 0 ) {
32
+ q .offer (prerequisites [i ][0 ]);
33
+ }
34
+ }
35
+ }
36
+
37
+ }
38
+ for (int i =0 ; i <inDegree .length ; i ++) {
39
+ if (inDegree [i ] != 0 ) {
40
+ return false ;
41
+ }
42
+ }
43
+ return true ;
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments