DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph

The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node, and with the help of that node, we visit the other adjacent nodes. Once all the vertices are done of a particular node, it moves further to check another node and its adjacent vertices.

For example -  We start to search from vertex 2. It has 2 adjacent vertices(0 and 3), it goes to them and prints 0 and 3. 0 also has an adjacent vertex 1, so it goes to one then prints 1. Since 3 does not have any adjacent vertex, we return.

Output will be 2 0 3 1.

Breadth First Search (BFS) for a Graph

The data structure used is as follows:

  1. STL list container: It stores what are the adjacent nodes to a particular node.
  2. Queue: This queue will be needed for BFS traversal.

Note: The code in this article uses an adjacency list representation of the graph.

Time Complexity: O(V+E), where V is the number of vertices in the graph and E is the number of edges in the graph.

C++ code:

include 
 using namespace std;
 // Create a graph class for adjacency implemenatation
 class Graph {
     int V; // Number of vertices in the graph
 // This list of integers stores the adjacent vertices to a node list<int>* adj;
 public:
     Graph(int V); // Constructor to initialize the number of vertices and list initialization
 void addEdge(int v, int w);  // The BFS traversal will be printed from a node void BFS_Algo(int s);
 };
 // Definition of constructor
 Graph::Graph(int V)
 {
     this->V = V;
     adj = new list[V];
 }
 // Definition adding a new edge
 void Graph::addEdge(int v, int w)
 {
     adj[v].push_back(w); // Add value to graph
 }
 void Graph::BFS_Algo(int s)
 {
     // As none of the vertext is visited mark all false
     bool* visited = new bool[V];
     for (int i = 0; i < V; i++)
         visited[i] = false;
 list<int> queue; // The node is enterted to qeue and marked visited visited[s] = true; queue.push_back(s); // The iterator iterates in the adjacent vertices list<int>::iterator i; while (!queue.empty()) {     s = queue.front(); // print the vertex which was dequeues from the queue     cout << s << " ";     queue.pop_front();     // If the visited vertex is not marked true, mark it true.     for (i = adj[s].begin(); i != adj[s].end(); ++i) {         if (!visited[*i]) {             visited[*i] = true;             queue.push_back(*i);         }     } }
 }
 int main() // Main function to add Graph vertices and call BFS
 {
 Graph g(4); // A graph with 4 nodes g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "The BFS traversal from Node 2 is : "; g.BFS_Algo(2); return 0; }

Java Code:

 import java.io.*;
 import java.util.*;
 // Create a graph class for adjacency implemenatation
 class Graph {
 private
     int V; // Number of vertices in the graph
     // This list of integers stores the adjacent vertices to a node
 private
     LinkedList<Integer> adj[];
     //  Constructor to initialize the number of vertices and list initialization
  
     Graph(int v)
     {
         V = v;
         adj = new LinkedList[v];
         for (int i = 0; i < v; ++i)
             adj[i] = new LinkedList();
     }
  
     void addEdge(int v, int w)    // Add new edge to graph
  
     {
         // Adding a new vertex
         adj[v].add(w);
     }
  
     // prints BFS traversal from a given source s
     void BFS_Algo(int s)
     {
         // Mark all the vertices as not visited(By default
         // set as false)
         boolean visited[] = new boolean[V];
  
         // Create a queue for BFS
         LinkedList<Integer> queue = new LinkedList<Integer>();
  
         // Mark the current node as visited
         visited[s] = true; // and enqueue it in queue
         queue.add(s);
         // Iteate in queue
         while (queue.size() != 0) {
             // Take a vertex from queue and print it
  
             s = queue.poll();
             System.out.print(s + " ");
  
             // If any adjacent has not marked true mark it true
             // and add it to the queue
             Iterator<Integer> i = adj[s].listIterator(); // get current value
             while (i.hasNext()) {
                 int n = i.next();
                 if (!visited[n]) {
                     visited[n] = true;
                     queue.add(n);
                 }
             }
         }
     }
  
 public static void main(String args[]) // Main function of java to add vertices and call BFS
     {
         Graph g = new Graph(4);
  
         g.addEdge(0, 1);
         g.addEdge(0, 2);
         g.addEdge(1, 2);
         g.addEdge(2, 0);
         g.addEdge(2, 3);
         g.addEdge(3, 3);
  
         System.out.println("Following is Breadth First Traversal " + "(starting from vertex 2)");
  
         g.BFS_Algo(2);
     }
 }
   

Related Topics

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.