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+ * @param {number } numCourses
3+ * @param {number[][] } prerequisites
4+ * @return {boolean }
5+ */
6+ var canFinish = function ( numCourses , prerequisites ) {
7+ // Initialize in-degree array and graph map
8+ const inDegree = Array ( numCourses ) . fill ( 0 ) ;
9+ const graph = new Map ( ) ;
10+
11+ // Build the graph and compute in-degrees
12+ prerequisites . forEach ( ( [ course , pre ] ) => {
13+ inDegree [ course ] ++ ;
14+ if ( ! graph . has ( pre ) ) {
15+ graph . set ( pre , [ ] ) ;
16+ }
17+ graph . get ( pre ) . push ( course ) ;
18+ } ) ;
19+
20+ // Queue for courses with no prerequisites
21+ const queue = [ ] ;
22+ for ( let i = 0 ; i < numCourses ; i ++ ) {
23+ if ( inDegree [ i ] === 0 ) {
24+ queue . push ( i ) ;
25+ }
26+ }
27+
28+ // Process the courses
29+ let count = 0 ;
30+ while ( queue . length > 0 ) {
31+ const course = queue . shift ( ) ;
32+ count ++ ;
33+ if ( graph . has ( course ) ) {
34+ graph . get ( course ) . forEach ( ( nextCourse ) => {
35+ inDegree [ nextCourse ] -- ;
36+ if ( inDegree [ nextCourse ] === 0 ) {
37+ queue . push ( nextCourse ) ;
38+ }
39+ } ) ;
40+ }
41+ }
42+
43+ // Return true if all courses can be finished
44+ return count === numCourses ;
45+ } ;
46+
47+ // TC: O(V + E)
48+ // V is the number of courses, E is the number of prerequisites.
49+ // SC: O(V + E)
You can’t perform that action at this time.
0 commit comments