File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * TC: O(V + E)
3+ * SC: O(V + E)
4+ * N: numCourses(all of vertex), P: prerequisites(all of edge)
5+ */
6+
7+ /**
8+ * @param {number } numCourses
9+ * @param {number[][] } prerequisites
10+ * @return {boolean }
11+ */
12+ var canFinish = function ( numCourses , prerequisites ) {
13+ const STEP = {
14+ before : 0 ,
15+ ing : 1 ,
16+ after : 2 ,
17+ } ;
18+ const stepBoard = Array . from ( { length : numCourses } , ( ) => STEP . before ) ;
19+ const board = Array . from ( { length : numCourses } , ( ) => [ ] ) ;
20+
21+ for ( const [ a , b ] of prerequisites ) {
22+ board [ a ] . push ( b ) ;
23+ }
24+
25+ for ( let index = 0 ; index < numCourses ; index ++ ) {
26+ if ( isCycle ( index ) ) {
27+ return false ;
28+ }
29+ }
30+ return true ;
31+
32+ function isCycle ( current ) {
33+ if ( stepBoard [ current ] === STEP . end ) {
34+ return false ;
35+ }
36+ if ( stepBoard [ current ] === STEP . ing ) {
37+ return true ;
38+ }
39+
40+ stepBoard [ current ] = STEP . ing ;
41+ for ( const next of board [ current ] ) {
42+ if ( isCycle ( next ) ) {
43+ return true ;
44+ }
45+ }
46+ stepBoard [ current ] = STEP . end ;
47+ return false ;
48+ }
49+ } ;
You can’t perform that action at this time.
0 commit comments