In previous posts, the depth-first traversal of graphs was introduced, and recursive and non-recursive implementations were carried out respectively. BFS cannot be implemented recursively, and the most widespread implementation is the use of queues. This is very similar to the DFS stack implementation, and even the code rarely needs to be changed. Starting at the given start node, all its neighboring nodes are then crammed into the queue, each time a node is accessed, its pop () is queued, and its neighboring nodes are also crammed into the queue. The algorithm ends until the queue is empty.
The implementation of the code is not much of a hindrance, C + + implementation:
1#include <iostream>2#include <queue>3 using namespacestd;4 5 #defineMAX 206 #defineSTART 17 8 intVisited[max];9 intMap[max][max];Ten One voidBFsintStartintN) { Aqueue<int>Q; - intQ_top; -cout<<start<<" "; theVisited[start] =1; - for(inti =1; I <= N; i++ ) { - if(Map[start][i] = =1&& Visited[i] = =0){ - Q.push (i); +Visited[i] =1; - } + } A while(!Q.empty ()) { atQ_top =Q.front (); - Q.pop (); -cout<<q_top<<" "; - for(inti =1; I <= N; i++ ){ - if(Map[q_top][i] = =1&& Visited[i] = =0){ - Q.push (i); inVisited[i] =1; - } to } + } - the } * $ intMainintargcConst Char*argv[]) {Panax Notoginseng intnum_vex,num_edge,x,y; -cout<<"Input number of nodes and edges >>"; theCin>>num_vex>>Num_edge; + for(intI=0; i<max;i++){ A for(intj =0; J < max;j++){ theMAP[I][J] =0; + } - } $ for(inti =1; I <= num_vex;i++){ $Visited[i] =0; - } -cout<<"Input edges,"<<num_edge<<"Left >>"; the for(inti =1; I <= num_edge;i++){ -Cin>>x>>y;WuyiMap[x][y] = map[y][x] =1; thecout<<"Input edges,"<< (num_edge-i) <<"Left >>"; - } Wu BFS (START, Num_vex); - return 0; About}
Graph breadth-first/hierarchical Traversal (BFS) C + + queue implementation