Advertisement
Evirir

Untitled

Dec 23rd, 2018
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> adj[100];       //adjacency list (an array of vectors)
  5. bool visited[100];      //to keep track which vertices are visited
  6. queue<int> Q;           //queue of incoming vertices to check
  7.  
  8. void BFS(int v){
  9.     Q.push(v);          //insert root vertex (vertex 0)
  10.     visited[v]=true;    //mark as visited
  11.                
  12.     while(!Q.empty()){          //repeat while the queue is not empty
  13.        
  14.         int now=Q.front();      //take frontmost vertex as current vertex
  15.         cout<<now<<" ";         //prints out current vertex
  16.         Q.pop();                //remove the frontmost element
  17.        
  18.         //check each vertex connected to current vertex
  19.         for(int i=0;i<adj[now].size();i++){
  20.             int x=adj[now][i];
  21.             if(!visited[x]){        //if vertex is not visited, add it to the (back of) queue
  22.                 visited[x]=true;
  23.                 Q.push(x);
  24.             }
  25.         }
  26.     }
  27. }
  28.  
  29. int main()
  30. {
  31.     int V,E; //specify no of vertices,V and edges,E
  32.     cin>>V>>E;
  33.    
  34.     //create adjacency list (input E pairs of vertices that are connected by an edge)
  35.     for(int i=0;i<E;i++){
  36.         int a,b;
  37.         cin>>a>>b;
  38.         adj[a].push_back(b);
  39.         adj[b].push_back(a);
  40.     }
  41.    
  42.     BFS(0); //start BFS from vertex 0
  43.    
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement