Home | Projects | Notes > Data Structures & Algorithms > Breadth-First Search (BFS)

Breadth-First Search (BFS)

 

Breadth-First Search (BFS)

Algorithm

  1. Initialize a queue (FIFO) data structure to keep track of nodes to be visited. Enqueue the starting node into the queue.

  2. Initialize a set or array to keep track of visited nodes to avoid revisiting them. Mark the starting node as visited.

  3. While the queue is not empty:

    1. Dequeue a node from the front of the queue.

    2. Process the node (print its value, perform some operation, etc.)

    3. Enqueue all unvisited neighbors of the current node into the queue and mark them as visited.

  4. Continue the process until the queue becomes empty, meaning all nodes have been visited.

Pseudo-code

In this algorithm,

  • Graph represents the graph or data structure you're traversing

  • startNode is the initial node from which you want to start the traversal

  • neighbors of currentNode refers to the neighboring nodes of the current node that are connected by edges.

 

Code (C++)

 

Code (C)

The order of traversal in BFS can vary depending on the order in which neighbors are added to the queue. Both orders are correct as long as they follow the BFS traversal rules.

In the output "0 2 1 4 3 5", the BFS algorithm is traversing the graph layer by layer, but the order of adding neighbors to the queue might be slightly different. For example, in this case, after visiting node 0, the algorithm enqueues nodes 1 and 2. Node 2 is dequeued before node 1, which is why you see node 2 being visited before node 1.

So, the BFS algorithm is still correctly traversing the graph, but the order of neighbors' processing might differ based on implementation details such as the queue's behavior and order of enqueuing nodes. Both "0 1 2 3 4 5" and "0 2 1 4 3 5" are valid BFS traversal orders for the given graph and its edges.