Graph breadth-first/hierarchical Traversal (BFS) C + + queue implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.