From c02bd1451f4ee50bb33323e27cd3832b30645b7b Mon Sep 17 00:00:00 2001 From: Anthony Sim Date: Wed, 6 Jul 2022 16:48:51 -0700 Subject: [PATCH] 207 course schedule --- javascript/207-canFinish.js | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 javascript/207-canFinish.js 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