apl-mhd

BFS

Apr 12th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3.  
  4. using namespace std;
  5.  
  6. queue<int> number;
  7.  
  8.  
  9. int graph[50][50] = {0};
  10.  
  11. int edges, vertices;
  12.  
  13. int visited[100] = {0};
  14.  
  15. void graphInput(){
  16.        
  17.     cout<<"Input number of vertices"<<endl;
  18.     cin>>vertices;
  19.     cout<<"Input number of edges"<<endl;
  20.     cin>>edges;
  21.     int v1, v2;
  22.    
  23.    
  24.     for(int i=1; i<edges+1; i++){
  25.            
  26.             cin>>v1>>v2;
  27.             graph[v1][v2]=1;
  28.             graph[v2][v1]=1;
  29.        
  30.         }
  31.    
  32.     }
  33.    
  34. bool isVisited(int v){
  35.    
  36.     for(int i=0; i<100; i++){
  37.     if(visited[i] == v)
  38.         return true;
  39.    
  40.    
  41.     }
  42. return false;
  43. }
  44. void BFS(){
  45.     number.push(2);
  46.     int t,index=0;
  47.     while(!number.empty()){
  48.        
  49.         t = number.front();
  50.         number.pop();
  51.         for(int i =1; i<=vertices; i++){
  52.            
  53.             if(graph[t][i]){
  54.                
  55.                 if(isVisited(i) == false )
  56.                     number.push(i);        
  57.                 }
  58.                        
  59.             }
  60.        
  61.        
  62.         if(isVisited(t) == false)
  63.             visited[index++] = t;
  64.        
  65.     }
  66.    
  67. }  
  68.  
  69.  
  70. void displayGraph(){   
  71.     for(int i=1; i<=vertices; i++){
  72.             cout<<i<<"->";
  73.         for(int j=1; j<=vertices; j++){
  74.                 if(graph[i][j])
  75.                     cout<<j<<" ";
  76.             }
  77.            
  78.             cout<<endl;
  79.        
  80.         }
  81.    
  82. }
  83.  
  84. int main(int argc, char **argv)
  85. {
  86.    
  87.     graphInput();
  88.     BFS();
  89.     displayGraph();
  90.     for(int i=0; i<=vertices; i++){
  91.    
  92.         if(visited[i] >0)
  93.             cout<<visited[i]<<" ";
  94.     }
  95.    
  96.    
  97.    
  98.     return 0;
  99. }
Add Comment
Please, Sign In to add comment