diff --git a/Data Structures/dfs.js b/Data Structures/dfs.js new file mode 100644 index 0000000..31726a7 --- /dev/null +++ b/Data Structures/dfs.js @@ -0,0 +1,25 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/depth-first-search + +function dfs(graph, root) { + const n_nodes = graph[0].length; + const reachable = new Set([root]); + const stack = [root]; + while (stack.length) { + const node = stack.pop(); + for (let i = 0; i < n_nodes; i++) { + if (graph[node][i] > 0 && !reachable.has(i)) { + reachable.add(i); + stack.push(i); + } + } + } + return Array.from(reachable); +} + +var exDFSGraph = [ + [0, 1, 0, 0], + [1, 0, 1, 0], + [0, 1, 0, 1], + [0, 0, 1, 0], +]; +console.log(dfs(exDFSGraph, 3));