import { GraphNode } from '../graphs/graph-node' /** * Perform a depth-first search through a directed graph. * * Time complexity: O(V+E) * Space complexity: O(V) * * @param {GraphNode} startNode * @param {Map, Array>} graph * @return {Array>} */ export const dfs = (startNode: GraphNode, graph: Map, Array>>) => { const output: Array = new Array() const visited = new Set>() recurse(startNode, graph, visited, output) return output } const recurse = ( root: GraphNode, graph: Map, Array>>, visited: Set>, output: Array ): void => { output.push(root.val) visited.add(root) const children = graph.get(root) if (!children) throw new Error('Children shouldnt be null') // loop through children of root and recurse for (const child of children) { if (!visited.has(child)) recurse(child, graph, visited, output) } }