File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-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+ var canFinish = function ( numCourses , prerequisites ) {
7+ // 1. ์ธ์ ๋ฆฌ์คํธ์ ์ง์
์ฐจ์ ๋ฐฐ์ด ์ด๊ธฐํ
8+ const graph = new Array ( numCourses ) . fill ( null ) . map ( ( ) => [ ] ) ;
9+ const inDegree = new Array ( numCourses ) . fill ( 0 ) ;
10+
11+ // 2. ๊ทธ๋ํ ๊ตฌ์ฑ ๋ฐ ์ง์
์ฐจ์ ๊ณ์ฐ
12+ for ( const [ course , prereq ] of prerequisites ) {
13+ graph [ prereq ] . push ( course ) ;
14+ inDegree [ course ] ++ ; // course์ ์ง์
์ฐจ์ ์ฆ๊ฐ
15+ }
16+
17+ // 3. ์ง์
์ฐจ์๊ฐ 0์ธ ๋
ธ๋๋ค์ ํ์ ์ถ๊ฐ
18+ const queue = [ ] ;
19+ for ( let i = 0 ; i < numCourses ; i ++ ) {
20+ if ( inDegree [ i ] === 0 ) {
21+ queue . push ( i ) ;
22+ }
23+ }
24+
25+ // 4. ์์ ์ ๋ ฌ ์ํ
26+ let processedCourses = 0 ;
27+
28+ while ( queue . length > 0 ) {
29+ const current = queue . shift ( ) ;
30+ processedCourses ++ ;
31+
32+ // ํ์ฌ ๋
ธ๋์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ๋
ธ๋์ ์ง์
์ฐจ์ ๊ฐ์
33+ for ( const neighbor of graph [ current ] ) {
34+ inDegree [ neighbor ] -- ;
35+
36+ // ์ง์
์ฐจ์๊ฐ 0์ด ๋๋ฉด ํ์ ์ถ๊ฐ
37+ if ( inDegree [ neighbor ] === 0 ) {
38+ queue . push ( neighbor ) ;
39+ }
40+ }
41+ }
42+
43+ // 5. ๋ชจ๋ ๊ฐ์๋ฅผ ์ฒ๋ฆฌํ๋์ง ํ์ธ
44+ return processedCourses === numCourses ;
45+ } ;
You canโt perform that action at this time.
0 commit comments