Advertisement
Guest User

BFS

a guest
Jul 25th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include<iostream>
  2. #include<queue>
  3. #include<vector>
  4. using namespace std;
  5. int main()
  6. {
  7. int edges,a,b;
  8. vector<int>nodes[1000];
  9. cout<<"Enter the no of edges"<<endl;
  10.     cin>>edges;
  11.     for(int i=0;i<edges;i++){
  12.         cin>>a>>b;
  13.         nodes[a].push_back(b);
  14.         nodes[b].push_back(a);
  15.     }
  16.  
  17.     cout<<endl;
  18.     //Adj list representation
  19. for(int i=0;i<1000;i++)
  20. {
  21.     if(!nodes[i].empty())
  22.     {   cout<<"[ "<<i<<" ]"<<"-->";
  23.         for(vector<int>::iterator it=nodes[i].begin();
  24.                 it!=nodes[i].end();++it)
  25.         {
  26.         cout<<*it<<"-->";
  27.         }
  28.         cout<<"NULL"<<endl;
  29.     }
  30. }
  31.  
  32. queue<int> que;
  33. //initially que is empty
  34. bool visited[1000];
  35. // mark all the vertices as not visited
  36. for(int i=0;i<1000;i++)
  37. visited[i]=false;
  38.  
  39. int start;
  40. cout<<"\nEnter the starting node"<<endl;
  41. cin>>start;
  42.  
  43. //insert the starting node into the queue
  44. que.push(start);
  45. //mark the starting node as visited
  46. visited[start]=true;
  47.  
  48.  
  49.     cout<<"\nBFS Traversal\n";
  50.  
  51. while(!que.empty())
  52. {
  53.         //Dequeue a vertex from que and print it
  54.         int front = que.front();
  55.         cout<<front<<" ";
  56.         que.pop();
  57. // get all adjacent vertices of the dequeued vertex s
  58.      // If an adjacent vertex has not been visited,
  59.        //then mark it as visited
  60.         // and enqueue it
  61.     for(vector<int>::iterator it=nodes[front].begin();
  62.         it!=nodes[front].end();++it)
  63.         {
  64.             if(visited[*it]==false)
  65.             {
  66.                 visited[*it]=true;
  67.                 que.push(*it);
  68.             }
  69.         }
  70. }
  71.  
  72.     cout<<endl;
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement