Skip to content

New Feature-feat: added [breathFirstSearch] algorithm. #6

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
35 changes: 35 additions & 0 deletions algorithms/searching/breathFirstSearch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
function bfs (graph, start) {
//Queue that the nodes have to visited yet
var queue = [];
//Add node to start from
queue.push(start);
//A boolean array if we already visited a node
var visited = [];
//the start node is already visited
visited[start] = true;
// Keeping the distances (might not be necessary depending on your use case)
var distances = [];
distances[start] = 0;
//While there are nodes left to visit
while (queue.length > 0) {
console.log(visited);
console.log(distances);
var node = queue.shift();
console.log("Removing node " + node + " from the queue");
//for all neighboring nodes that haven't been visited yet
for (var i = 1; i < graph[node].length; i++) {
if (graph[node][i] && !visited[i]) {
visited[i] = true;
distances[i] = distances[node] + 1;
queue.push(i);
console.log("Visiting node " + i + ", setting its distance to " + distances[i] + " and adding it to the queue");

}
}
}
return distances;
}