From 96a8f58c36e3fe81bfe12cd10122aed3f06292ea Mon Sep 17 00:00:00 2001 From: Abhay narayan singh <33628155+Abhaynarayansingh-mriirs@users.noreply.github.com> Date: Wed, 3 Oct 2018 14:57:44 +0530 Subject: [PATCH 1/2] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 153f9ca..f9f2f84 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ # Algorithms +this is an algorithm From 8bad1c2b2bde233ea6a022071e3bb56189f27a94 Mon Sep 17 00:00:00 2001 From: Abhay narayan singh <33628155+Abhaynarayansingh-mriirs@users.noreply.github.com> Date: Mon, 11 Feb 2019 22:54:41 +0530 Subject: [PATCH 2/2] Create breadthFirstSearch.js --- breadthFirstSearch.js | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 breadthFirstSearch.js diff --git a/breadthFirstSearch.js b/breadthFirstSearch.js new file mode 100644 index 0000000..4309754 --- /dev/null +++ b/breadthFirstSearch.js @@ -0,0 +1,55 @@ +import Queue from '../../../data-structures/queue/Queue'; + +function initCallbacks(callbacks = {}) { + const initiatedCallback = callbacks; + + const stubCallback = () => {}; + + const allowTraversalCallback = ( + () => { + const seen = {}; + return ({ nextVertex }) => { + if (!seen[nextVertex.getKey()]) { + seen[nextVertex.getKey()] = true; + return true; + } + return false; + }; + } + )(); + + initiatedCallback.allowTraversal = callbacks.allowTraversal || allowTraversalCallback; + initiatedCallback.enterVertex = callbacks.enterVertex || stubCallback; + initiatedCallback.leaveVertex = callbacks.leaveVertex || stubCallback; + + return initiatedCallback; +} + + +export default function breadthFirstSearch(graph, startVertex, originalCallbacks) { + const callbacks = initCallbacks(originalCallbacks); + const vertexQueue = new Queue(); + + // Do initial queue setup. + vertexQueue.enqueue(startVertex); + + let previousVertex = null; + + // Traverse all vertices from the queue. + while (!vertexQueue.isEmpty()) { + const currentVertex = vertexQueue.dequeue(); + callbacks.enterVertex({ currentVertex, previousVertex }); + + // Add all neighbors to the queue for future traversals. + graph.getNeighbors(currentVertex).forEach((nextVertex) => { + if (callbacks.allowTraversal({ previousVertex, currentVertex, nextVertex })) { + vertexQueue.enqueue(nextVertex); + } + }); + + callbacks.leaveVertex({ currentVertex, previousVertex }); + + // Memorize current vertex before next loop. + previousVertex = currentVertex; + } +}