|
| 1 | +// Time Complexity: O(m * n) |
| 2 | +// Space Complexity: O(m * n) |
| 3 | + |
| 4 | +// initialize an array to keep track of the in-degrees for each course |
| 5 | +let inDegree = new Array(numCourses).fill(0); |
| 6 | +// initialize an adjacency list to represent the graph of courses |
| 7 | +let adjList = new Array(numCourses).fill(0).map(() => []); |
| 8 | + |
| 9 | +// fill the in-degree array and adjacency list based on the prerequisites |
| 10 | +for (let [course, prereq] of prerequisites) { |
| 11 | + // increment the in-degree of the course |
| 12 | + inDegree[course]++; |
| 13 | + // add the course to the adjacency list of the prerequisite |
| 14 | + adjList[prereq].push(course); |
| 15 | +} |
| 16 | + |
| 17 | +// initialize a queue to keep track of courses with no prerequisites (in-degree of 0) |
| 18 | +let queue = []; |
| 19 | +for (let i = 0; i < numCourses; i++) { |
| 20 | + if (inDegree[i] === 0) { |
| 21 | + queue.push(i); |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +// initialize a counter to keep track of the number of courses that have been processed |
| 26 | +let count = 0; |
| 27 | + |
| 28 | +// process the courses with no prerequisites |
| 29 | +while (queue.length > 0) { |
| 30 | + // get a course from the queue |
| 31 | + let current = queue.shift(); |
| 32 | + // increment the counter as this course can be taken |
| 33 | + count++; |
| 34 | + |
| 35 | + // iterate through the adjacency list of the current course |
| 36 | + for (let neighbor of adjList[current]) { |
| 37 | + // decrement the in-degree of the neighboring course |
| 38 | + inDegree[neighbor]--; |
| 39 | + // if in-degree becomes 0, add it to the queue |
| 40 | + if (inDegree[neighbor] === 0) { |
| 41 | + queue.push(neighbor); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// if the count of processed courses equals the total number of courses, return true |
| 47 | +return count === numCourses; |
0 commit comments