There are numCourses courses. prerequisites[i] = [a, b] means you must take b before a. Return true if you can finish all courses.
Mark nodes white (new), gray (on the current path) or black (done). Reaching a gray node means a back edge, which is a cycle.
1function canFinish(numCourses: number, prerequisites: number[][]): boolean {2const adj: number[][] = Array.from({ length: numCourses }, () => []);3for (const [a, b] of prerequisites) adj[b].push(a);4const state = new Array(numCourses).fill(0); // 0 white, 1 gray, 2 black5function hasCycle(u: number): boolean {6if (state[u] === 1) return true;7if (state[u] === 2) return false;8state[u] = 1;9for (const v of adj[u]) if (hasCycle(v)) return true;10state[u] = 2;11return false;12}13for (let i = 0; i < numCourses; i++) if (hasCycle(i)) return false;14return true;15}
Build the adjacency list.
Space: play/pause · ←/→: step