File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+ public boolean canFinish (int numCourses , int [][] prerequisites ) {
3
+ int [] degree = new int [numCourses ];
4
+
5
+ Map <Integer , List <Integer >> graph = new HashMap <>();
6
+
7
+ for (int [] p : prerequisites ) {
8
+ int course = p [0 ];
9
+ int pre = p [1 ];
10
+
11
+ degree [course ]++;
12
+
13
+ if (!graph .containsKey (pre )) {
14
+ graph .put (pre , new ArrayList <>());
15
+ }
16
+ graph .get (pre ).add (course );
17
+ }
18
+
19
+ Queue <Integer > q = new LinkedList <>();
20
+ for (int i = 0 ; i < numCourses ; i ++) {
21
+ if (degree [i ] == 0 ) {
22
+ q .offer (i );
23
+ }
24
+ }
25
+
26
+ int finishedCourses = 0 ;
27
+
28
+ while (!q .isEmpty ()) {
29
+ int curr = q .poll ();
30
+ finishedCourses ++;
31
+
32
+ if (graph .containsKey (curr )) {
33
+ for (int neighbor : graph .get (curr )) {
34
+ degree [neighbor ]--;
35
+ if (degree [neighbor ] == 0 ) {
36
+ q .offer (neighbor );
37
+ }
38
+ }
39
+ }
40
+ }
41
+
42
+ if (finishedCourses == numCourses ) return true ;
43
+
44
+ return false ;
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments