Let's code out a general BFS algorithm printing each vertex's value in a BFS order. We are given ana graph in the form of an adjacency list, as well as a starting vertex.
Pseudocode
1. Create a queue to hold neighbor vertices and add the start vertex.
2. Create a set to track visited vertices and add the start vertex.
3. While queue is not empty
4. Dequeue from the queue and set to current.
5. Loop through all the vertex's neighbors.
6. For each neighbor, check if the vertex has been visited.
7. If not visited, then add it to the queue and add mark it as visited.
8. Operate on current
9. Once the queue is empty, we have completed the BFS
Pseudocode
1. Create a queue to hold neighbor vertices and add the start vertex.
2. Create a set to track visited vertices and add the start vertex.
3. While queue is not empty
4. Dequeue from the queue and set to current.
5. Loop through all the vertex's neighbors.
6. For each neighbor, check if the vertex has been visited.
7. If not visited, then add it to the queue and add mark it as visited.
8. Operate on current
9. Once the queue is empty, we have completed the BFS
here'sHere's the code in javascriptJavaScript:
function graphBFS(graph, start) {
let queue = new Queue(); // 1
let visited = new Set(); // 1
let current; // 1
let neighbors; // 1
queue.enqueue(start); // 1
visited.add(start); // 1
// while loop will run a total of V times
while (queue.length > 0) { // 1 (for break condition)
current = queue.dequeue(); // 1
neighbors = graph.neighbors(current); // 1 (for adjacency list)
// the for loop will run based on d (degree) on average is E/V
for (let i = 0; i < neighbors.length; i++) { // 1
if (!visited.has(neighbors[i]) { // 1
queue.enqueue(neighbors[i]); // 1
visited.add(neighbors[i]); // 1
}
// <-- operating on the current vertex will add additional time
}
}
}
function graphBFS(graph, start) {
let queue = new Queue(); // 1
let visited = new Set(); // 1
let current; // 1
let neighbors; // 1
queue.enqueue(start); // 1
visited.add(start); // 1
// while loop will run a total of V times
while (queue.length > 0) { // 1 (for break condition)
current = queue.dequeue(); // 1
neighbors = graph.neighbors(current); // 1 (for adjacency list)
// the for loop will run based on d (degree) on average is E/V
for (let i = 0; i < neighbors.length; i++) { // 1
if (!visited.has(neighbors[i]) { // 1
queue.enqueue(neighbors[i]); // 1
visited.add(neighbors[i]); // 1
}
// <-- operating on the current vertex will add additional time
}
}
}