File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ // n: numCourses, p: len(prerequisites)
2+ // Time complexity: O(n + p)
3+ // Space complexity: O(n + p)
4+
5+ class _Queue {
6+ constructor ( ) {
7+ this . q = [ ] ;
8+ this . start = 0 ;
9+ this . end = 0 ;
10+ }
11+
12+ isEmpty ( ) {
13+ return this . start === this . end ;
14+ }
15+
16+ push ( value ) {
17+ this . q . push ( value ) ;
18+ this . end ++ ;
19+ }
20+
21+ shift ( ) {
22+ const rv = this . q [ this . start ] ;
23+ delete this . q [ this . start ++ ] ;
24+
25+ return rv ;
26+ }
27+ }
28+
29+ /**
30+ * @param {number } numCourses
31+ * @param {number[][] } prerequisites
32+ * @return {boolean }
33+ */
34+ var canFinish = function ( numCourses , prerequisites ) {
35+ const graph = Array . from ( { length : numCourses } , ( ) => [ ] ) ;
36+ const inDegree = Array . from ( { length : numCourses } , ( ) => 0 ) ;
37+
38+ for ( const [ end , start ] of prerequisites ) {
39+ graph [ start ] . push ( end ) ;
40+ inDegree [ end ] ++ ;
41+ }
42+
43+ const q = new _Queue ( ) ;
44+
45+ for ( let i = 0 ; i < numCourses ; i ++ ) {
46+ if ( inDegree [ i ] === 0 ) {
47+ q . push ( i ) ;
48+ }
49+ }
50+
51+ let count = 0 ;
52+
53+ while ( ! q . isEmpty ( ) ) {
54+ const current = q . shift ( ) ;
55+ count ++ ;
56+
57+ // ํ์ฌ ๋
ธ๋์ ์ฐ๊ฒฐ๋ ๋ค๋ฅธ ๋
ธ๋์ ์ฐจ์ ๊ฐ์
58+ for ( const node of graph [ current ] ) {
59+ inDegree [ node ] -= 1 ;
60+
61+ if ( inDegree [ node ] === 0 ) {
62+ q . push ( node ) ;
63+ }
64+ }
65+ }
66+
67+ return count === numCourses ;
68+ } ;
You canโt perform that action at this time.
0 commit comments