Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. /*
  8. * This program reads a simple undireced graph from stdin and preforms
  9. * a BFS on the given graph. The format is as follows:
  10. * n m
  11. * e1 e2
  12. * ...
  13. *
  14. * The first line contains the number of vertices and edges of
  15. * the graph. The following m lines contain one edge each.
  16. * An edge is represented by two distinct integers between 0 and n-1,
  17. * being the two respective endpoints of the edge.
  18. *
  19. * */
  20.  
  21. void bfs(vector<vector<int> > & g, vector<int> & order){
  22. int n = (int)g.size();
  23. vector<bool> seen(n,false);
  24. queue<int> q;
  25. seen[0] = true;
  26. q.push(0);
  27. while(!q.empty()){
  28. int x = q.front();
  29. order.push_back(x);
  30. q.pop();
  31. for(auto y : g[x]){
  32. if(!seen[y]){
  33. q.push(y);
  34. seen[y] = true;
  35. }
  36. }
  37. }
  38. }
  39.  
  40. int main(){
  41.  
  42. //setting up the graph
  43. int n,m;
  44. cin >> n >> m;
  45. vector<vector<int> > g(n,vector<int> ());
  46. vector<int> order;
  47. while(m--){
  48. int a,b;
  49. cin >> a >> b;
  50. g[a].push_back(b);
  51. g[b].push_back(a);
  52. }
  53.  
  54. //bfs call
  55. bfs(g,order);
  56.  
  57. //printing the order
  58. cout << "One BFS order of the graph is:" << endl;
  59. for(auto x: order){
  60. cout << x << " ";
  61. }
  62. cout << endl;
  63.  
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement