Given a graph and a starting vertex print the value of each vertex in a breadth first order.
Let's code out a general BFS algorithm printing each vertex's value in a BFS order. We are given a graph in the form of an adjacency list, as well as a starting vertex.
To analyze the complexity of a graph, we need to consider the number of vertices (V) and the number of Edges (E) as independent variables. Also, we need to consider the type of edge representation for the graph. We will go over the analysis for adjacency list.
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's the code in JavaScript:
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
}
}
}