File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ // TC: O(n + p)
2
+ // n -> number of courses, p -> the length of prerequisites
3
+ // SC: O(n + m)
4
+ // n -> the length of the graph size, m -> the length of nested list's size
5
+ class Solution {
6
+ public boolean canFinish (int numCourses , int [][] prerequisites ) {
7
+ List <List <Integer >> graph = new ArrayList <>();
8
+ int [] inDegree = new int [numCourses ];
9
+
10
+ for (int i = 0 ; i < numCourses ; i ++) graph .add (new ArrayList <>());
11
+
12
+ for (int [] prerequisite : prerequisites ) {
13
+ int course = prerequisite [0 ];
14
+ int pre = prerequisite [1 ];
15
+ graph .get (pre ).add (course );
16
+ inDegree [course ] += 1 ;
17
+ }
18
+
19
+ Queue <Integer > q = new LinkedList <>();
20
+ for (int i = 0 ; i < numCourses ; i ++) {
21
+ if (inDegree [i ] == 0 ) q .offer (i );
22
+ }
23
+
24
+ int visitedCourses = 0 ;
25
+ while (!q .isEmpty ()) {
26
+ int course = q .poll ();
27
+ visitedCourses += 1 ;
28
+
29
+ for (int nextCourse : graph .get (course )) {
30
+ inDegree [nextCourse ] -= 1 ;
31
+ if (inDegree [nextCourse ] == 0 ) q .offer (nextCourse );
32
+ }
33
+ }
34
+
35
+ return visitedCourses == numCourses ;
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments