|
| 1 | +/** |
| 2 | + * @param {number} numCourses |
| 3 | + * @param {number[][]} prerequisites |
| 4 | + * @return {boolean} |
| 5 | + */ |
| 6 | + |
| 7 | +// ✅ Graph DFS (Depth-First Search) approach |
| 8 | +// Time Complexity: O(V + E), where V is the number of courses (numCourses) and E is the number of prerequisites (edges). |
| 9 | +// Space Complexity: O(V + E), where V is the number of courses and E is the number of prerequisites. |
| 10 | + |
| 11 | +var canFinish = function (numCourses, prerequisites) { |
| 12 | + // prerequisites = [ |
| 13 | + // [1, 0], // Course 1 depends on Course 0 |
| 14 | + // [2, 1], // Course 2 depends on Course 1 |
| 15 | + // [3, 1], // Course 3 depends on Course 1 |
| 16 | + // [3, 2] // Course 3 depends on Course 2 |
| 17 | + // ]; |
| 18 | + |
| 19 | + // graph = { |
| 20 | + // 0: [1], // Course 0 is a prerequisite for Course 1 |
| 21 | + // 1: [2, 3], // Course 1 is a prerequisite for Courses 2 and 3 |
| 22 | + // 2: [3], // Course 2 is a prerequisite for Course 3 |
| 23 | + // 3: [] // Course 3 has no prerequisites |
| 24 | + // }; |
| 25 | + |
| 26 | + // Build the graph |
| 27 | + const graph = {}; |
| 28 | + |
| 29 | + // for(let i=0; i<numCourses; i++) { |
| 30 | + // graph[i] = [] |
| 31 | + // } |
| 32 | + |
| 33 | + // Fill in the graph with prerequisites |
| 34 | + for (const [course, prereq] of prerequisites) { |
| 35 | + if (!graph[prereq]) { |
| 36 | + graph[prereq] = []; |
| 37 | + } |
| 38 | + graph[prereq].push(course); |
| 39 | + } |
| 40 | + |
| 41 | + const visited = new Array(numCourses).fill(0); |
| 42 | + |
| 43 | + const dfs = (course) => { |
| 44 | + if (visited[course] === 1) return false; // cycle detected! |
| 45 | + if (visited[course] === 2) return true; // already visited |
| 46 | + |
| 47 | + visited[course] = 1; |
| 48 | + |
| 49 | + // // Visit all the courses that depend on the current course |
| 50 | + for (const nextCourse of graph[course] || []) { |
| 51 | + if (!dfs(nextCourse)) { |
| 52 | + return false; // cycle detected! |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + visited[course] = 2; // fully visited and return true |
| 57 | + return true; |
| 58 | + }; |
| 59 | + |
| 60 | + // Check for each course whether it's possible to finish it |
| 61 | + for (let i = 0; i < numCourses; i++) { |
| 62 | + if (!dfs(i)) { |
| 63 | + return false; // cycle detected! |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return true; // no cycles |
| 68 | +}; |
| 69 | + |
0 commit comments