diff --git a/javascript/207-canFinish.js b/javascript/207-canFinish.js new file mode 100644 index 000000000..fe02f1f96 --- /dev/null +++ b/javascript/207-canFinish.js @@ -0,0 +1,38 @@ +function createGraph(numCourses, edges) { + const graph = Array.from({ length: numCourses }, () => []); + + for (let edge of edges) { + let [a, b] = edge; + + if (!(a in graph)) graph[a] = []; + if (!(b in graph)) graph[b] = []; + + graph[a].push(b); + } + return graph; +} + +function canFinish(numCourses, preq) { + const graph = createGraph(numCourses, preq); + let seen = new Set(); + let seeing = new Set(); + + function explore(course) { + if (seen.has(course)) return true; + if (seeing.has(course)) return false; + + seeing.add(course); + for (let neighbor of graph[course]) { + if (!explore(neighbor)) return false; + } + + seen.add(course); + seeing.delete(course); + return true; + } + + for (let i = 0; i < numCourses; i++) { + if (!explore(i)) return false; + } + return true; +}; \ No newline at end of file pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy