The breadth-first search basic idea of the graph and the hierarchical traversal of the tree are good. Unlike a tree's hierarchical traversal, the graph may contain loops, and we traverse through a node and continue the traversal, possibly returning to the already traversed node. To avoid traversing a node two times, you need to open up an array of type BOOL to mark whether the node has been traversed.
#include <iostream>#include<list>#include<queue>using namespacestd; //This class represents a directed graph using adjacency list representationclassGraph {Private: intV//Number of verticeslist<int> *adj;//Pointer to an array containing adjacency lists Public: Graph (intV);//Constructor voidAddedge (intVintW);//function to add a edge to graph voidBFS (ints);//Prints BFS tracersal from a given sources}; Graph::graph (intv) { This->v =v; Adj=Newlist<int>[v]; } voidGraph::addedge (intVintW) {adj[v].push_back (w);//Add W to V ' s list} 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 fo a 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); } }} cout<<Endl; } //Driver program to test methonds of graph classintMainintargcChar*argv[]) { //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<<"Followint is breadth first travesal (starting from vertex 2) \ n"; G.BFS (2); return 0; }
Output Result:
Following is breadth first traversal (starting from Vertex 2)
2 0 3 1
Breadth-first search for graphs