File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } numCourses
3
+ * @param {number[][] } prerequisites
4
+ * @return {boolean }
5
+ */
6
+ const canFinish = function ( numCourses , prerequisites ) {
7
+ const [ graph , inDegree ] = buildGraph ( numCourses , prerequisites )
8
+
9
+ const q = [ ]
10
+ for ( let i = 0 ; i < numCourses ; i ++ ) {
11
+ if ( inDegree . get ( i ) == null ) q . push ( i )
12
+ }
13
+ let num = 0
14
+ while ( q . length ) {
15
+ const pre = q . pop ( )
16
+ num ++
17
+ for ( const next of ( graph . get ( pre ) || [ ] ) ) {
18
+ inDegree . set ( next , inDegree . get ( next ) - 1 )
19
+ if ( inDegree . get ( next ) === 0 ) q . push ( next )
20
+ }
21
+ }
22
+ return num === numCourses
23
+
24
+
25
+ function buildGraph ( n , arr ) {
26
+ const res = new Map ( ) , inDegree = new Map ( )
27
+ for ( const [ cur , pre ] of arr ) {
28
+ if ( res . get ( pre ) == null ) res . set ( pre , new Set ( ) )
29
+ res . get ( pre ) . add ( cur )
30
+ if ( inDegree . get ( cur ) == null ) inDegree . set ( cur , 0 )
31
+ inDegree . set ( cur , inDegree . get ( cur ) + 1 )
32
+ }
33
+ return [ res , inDegree ]
34
+ }
35
+ } ;
36
+
37
+ // another
38
+
1
39
/**
2
40
* @param {number } numCourses
3
41
* @param {number[][] } prerequisites
You can’t perform that action at this time.
0 commit comments