From 1d1c0c9964843b26f8a3030954a0e9ef893bd578 Mon Sep 17 00:00:00 2001 From: Manish Date: Sat, 16 Sep 2023 13:11:25 +1000 Subject: [PATCH] Data Structures: Depth-First Search --- Data Structures/dfs.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Data Structures/dfs.js 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));