Advertisement
apl-mhd

BFS UPDATE

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