diff --git a/DIRECTORY.md b/DIRECTORY.md index cc807d5ff9..0ffeca5d2c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -70,8 +70,8 @@ * [CycleSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/CycleSort.js) * [FlashSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/FlashSort.js) * [GnomeSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/GnomeSort.js) - * [Heapsort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/Heapsort.js) * [HeapSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/HeapSort.js) + * [Heapsort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/Heapsort.js) * [InsertionSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/InsertionSort.js) * [MergeSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/MergeSort.js) * [QuickSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/QuickSort.js) diff --git a/Data-Structures/Graph/Graph.js b/Data-Structures/Graph/Graph.js index ef1a952a86..503d9b4981 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()