From be75ed68ed971143a8818aec193bc47dbdb1126c Mon Sep 17 00:00:00 2001 From: Manish Date: Fri, 15 Sep 2023 16:25:19 +1000 Subject: [PATCH] Data Structures: Breadth-First Search --- Data Structures/bfs.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Data Structures/bfs.js diff --git a/Data Structures/bfs.js b/Data Structures/bfs.js new file mode 100644 index 0000000..eefe275 --- /dev/null +++ b/Data Structures/bfs.js @@ -0,0 +1,34 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/breadth-first-search + +function bfs(graph, root) { + const nodesLen = {}; + const n_nodes = graph[root].length; + for (let dst = 0; dst < n_nodes; dst++) { + nodesLen[dst] = Infinity; + } + nodesLen[root] = 0; + for (let q = [root], d = 1; ; d++) { + const newQ = []; + for (let src of q) { + for (let dst = 0; dst < n_nodes; dst++) { + if (nodesLen[dst] > d && graph[src][dst] > 0) { + nodesLen[dst] = d; + newQ.push(dst); + } + } + } + if (newQ.length <= 0) { + break; + } + q = newQ; + } + return nodesLen; +} + +var exBFSGraph = [ + [0, 1, 0, 0], + [1, 0, 1, 0], + [0, 1, 0, 1], + [0, 0, 1, 0], +]; +console.log(bfs(exBFSGraph, 3));