From cb0aff9ec2fe6503fb79b7069c2dc37d6e2509f2 Mon Sep 17 00:00:00 2001 From: Sahil Date: Mon, 18 May 2020 10:15:53 +0530 Subject: [PATCH] Add Graph BFS algorithm (#169) * Add Graph BFS algorithm * updating DIRECTORY.md * Fix failing tests * updating DIRECTORY.md * Fix further failing tests Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- Data-Structures/Graph/Graph.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Data-Structures/Graph/Graph.js b/Data-Structures/Graph/Graph.js index ef1a952a8..503d9b498 100644 --- a/Data-Structures/Graph/Graph.js +++ b/Data-Structures/Graph/Graph.js @@ -30,6 +30,31 @@ class Graph { console.log(i + ' -> ' + vertex) } } + + /** + * Prints the Breadth first traversal of the graph from source. + * + * @param {number} source The source vertex to start BFS. + */ + bfs (source) { + const queue = [] + const visited = new Set() + queue.unshift([source, 0]) // level of source is 0 + visited.add(source) + while (queue.length) { + const front = queue[0] + const node = front[0] + const level = front[1] + queue.shift() // remove the front of the queue + console.log(`Visited node ${node} at level ${level}.`) + for (const next of this.adjacencyMap[node]) { + if (!visited.has(next)) { // not visited + queue.unshift([next, level + 1]) // level 1 more than current + visited.add(next) + } + } + } + } } const example = () => { @@ -37,8 +62,17 @@ const example = () => { g.addVertex(1) g.addVertex(2) g.addVertex(3) + g.addVertex(4) + g.addVertex(5) g.addEdge(1, 2) g.addEdge(1, 3) + g.addEdge(2, 4) + g.addEdge(2, 5) + console.log('Printing the adjacency list:\n') g.printGraph() + + // perform a breadth first search + console.log('\nBreadth first search at node 1:\n') + g.bfs(1) } example()