The breadth-first search (BFS) of the graph is similar to the tree's breadth-first search. Unlike a tree, there may be loops in the diagram . We may be able to access the same node again. For the surface to process the same node multiple times, we want the Boolean variable data record node to have been visited. To simplify, we assume that all nodes are accessible from the root node.
In the example, we start with Node 2. When we access to Node 0 o'clock, we look for all the nodes that are adjacent to him. Node 2 is the node that is adjacent to 0, and if we do not mark the node that has been accessed, then node 2 is repeatedly accessed. In this case, the algorithm will go on all the time. The result of a breadth-first search is 2,0,3,1.
The following C + + programs are a simple implementation of breadth-first search from a given node. The graph is stored using the Adjacency link list method. The STL list container is used to store adjacency nodes and node queues that are required for breadth-first search.
#include <list>#include<iostream>//Program-to -print BFS traversal from a given source vertex. BFS (int s)//traverses vertices reachable from susing namespacestd;//The class represents a directed graph using adjacency listsclassGraph {intV//No. of verticeslist<int> *adj; Public: Graph (intV);//Constructor~Graph (); destructorvoidAddedge (intVintW);//function to add a edge to graph voidBFS (ints);//print BFS traversal from a given source s}; Graph::graph (intV) { This->v =V; Adj=Newlist<int>[V];} Graph::~Graph () {Delete[]adj;}voidGraph::addedge (intVintW) {adj[v].push_back (w);}voidGRAPH::BFS (ints) {//Mark All, vertices as not visited BOOL*visited =New BOOL[V]; for(inti =0; i < V; i++) {Visited[i]=false; } //Create a queue for BFSlist<int>queue; //Mark The current node as visited and enqueue itVisited[s] =true; Queue.push_back (s); //"I" 'll be used-get all adjacent vertices of vertexlist<int>:: Iterator i; while(!Queue.empty ()) { //Dequeue a vertex from queue and print its =Queue.front (); cout<<s<<" "; Queue.pop_front (); //Get All adjacent vertices of the dequeued vertex s//If A adjacent have not been visited and then mark it visited//and Enqueue it for(i = Adj[s].begin (); I! = Adj[s].end (); i++) { if(!visited[*i]) {visited[*i] =true; Queue.push_back (*i); } } } Delete[]visited;}intMain () {//Create A graph given in the above diagramGraph g (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); cout<<"Following is breadth first traversal (starting from vertex 2) \ n"; G.BFS (2); return 0;}
Resources
1. http://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/
Breadth-First search for "data structure" graphs