2
* @param {number} numCourses3
* @param {number[][]} prerequisites6
var findOrder = function (numCourses, prerequisites) {7
let visiting = new Set();8
const visited = new Set();9
const adjList = new Map();12
// Generate scaffold of adjacency list13
// initialized with no prereqs14
for (let i = 0; i < numCourses; i++) {18
// Fill adjacency list with course prereqs20
// Value is any course prereqs21
for (const item of prerequisites) {22
const [course, prereq] = item;23
adjList.get(course).push(prereq);26
const dfs = (node) => {27
// We've already traversed down this path before28
// and determined that it isn't cyclical29
if (visited.has(node)) return true;31
// Visiting keeps track of what we've seen32
// during this current traversal and determines33
// if we have a cycle.34
if (visiting.has(node)) return false;36
// Mark this node as part of the current traversal39
// Get all adjacent nodes to traverse40
// traverse them in a loop looking for cycles41
const children = adjList.get(node);42
for (const child of children) {43
if (!dfs(child)) return false;46
// Ensures we don't re-traverse already traversed nodes since47
// we've already determined they contain no cycles.50
// Add this node to the result stack to return at the end55
for (const node of adjList.keys()) {56
if (!dfs(node)) return [];