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+ function createGraph ( numCourses , edges ) {
2+ const graph = Array . from ( { length : numCourses } , ( ) => [ ] ) ;
3+
4+ for ( let edge of edges ) {
5+ let [ a , b ] = edge ;
6+
7+ if ( ! ( a in graph ) ) graph [ a ] = [ ] ;
8+ if ( ! ( b in graph ) ) graph [ b ] = [ ] ;
9+
10+ graph [ a ] . push ( b ) ;
11+ }
12+ return graph ;
13+ }
14+
15+ function canFinish ( numCourses , preq ) {
16+ const graph = createGraph ( numCourses , preq ) ;
17+ let seen = new Set ( ) ;
18+ let seeing = new Set ( ) ;
19+
20+ function explore ( course ) {
21+ if ( seen . has ( course ) ) return true ;
22+ if ( seeing . has ( course ) ) return false ;
23+
24+ seeing . add ( course ) ;
25+ for ( let neighbor of graph [ course ] ) {
26+ if ( ! explore ( neighbor ) ) return false ;
27+ }
28+
29+ seen . add ( course ) ;
30+ seeing . delete ( course ) ;
31+ return true ;
32+ }
33+
34+ for ( let i = 0 ; i < numCourses ; i ++ ) {
35+ if ( ! explore ( i ) ) return false ;
36+ }
37+ return true ;
38+ } ;
You can’t perform that action at this time.
0 commit comments