Breadth First Search (BFS) - Algorithm - Graph Traversal

"What is Breadth First Search (BFS) ?"
  • BFS is an algorithm for traversing the Graph Data Structure.  
  • We can start from any arbitrary node in the Graph. This algorithm explores the neighbor nodes which are at the current level first and then it moves to the next level neighbors.
  • If all the edges in a graph are of the same weight, then BFS can also be used to find the minimum distance between the nodes in a graph.
Algorithm for BFS :

1.while all the vertices are not visited :
    2.enqueue(starting vertex) 
    3.while(queue is not empty) :
            4. Remove the current vertex from the queue and mark it as visited
            5. Find neighbors of the current vertex
            6. Iterate through all neighbors and add them to queue if they are not visited and mark them visited

Here one can wonder why we are doing Step 1?
    So, to answer that, it takes care of a special case of a disconnected graph where some nodes are disconnected from the main chunk of the graph. See figure below :


So, in the above graph, we can see that node with value 0 is disconnected from the main chunk of the graph. If we do not use the while loop of step 1 we end up traversing the connected parts only (parts which are connected to start vertex, if the start vertex is not node 0 obviously)

The implementation BFS traversal for all 6 types of graphs is exactly the same.

I will be writing two BFS traversals for two graphs - one implemented using adjacency matrix and other implemented using adjacency list.


2. BFS Traversal - Unweighted Undirected Graph implemented using Adjacency List

Comments

Popular posts from this blog

Binary Heap - Introduction

Divide and Conquer - Introduction

Bubble Sort