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

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: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 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: 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,...

5 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.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a 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 bubble sort technique...

4 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: 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: 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.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 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.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 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.

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: 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.

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: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.