Advertisement
apl-mhd

DFS

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