Skip to content

Add Graph BFS algorithm #169

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions Data-Structures/Graph/Graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,49 @@ 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 = () => {
const g = new Graph()
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()