VasilM

BFS_example

Dec 6th, 2012
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int MAXN = 100;
  5. int used[MAXN+1],Q[MAXN],P[MAXN],G[MAXN][MAXN] = {0},N, b,e;
  6.  
  7. void make_empty(){b=0;e=-1;}
  8.  
  9. void push(int x){Q[++e]=x;}
  10.  
  11. int pop(){return Q[b++];}
  12.  
  13. bool emptyQ(){return b>e;}
  14.  
  15. void BFS(int r) {
  16.   int  x,y,i; for(i=1;i<=N;i++) used[i]=0;
  17.   make_empty();push(r);used[r]=1;P[r]=0;
  18.   while(!emptyQ()) {  
  19.     x=pop();
  20.     for(i=1;i<=G[x][0];i++) {  
  21.       y=G[x][i];
  22.       if(!used[y]) {push(y);used[y]=1;P[y]=x;}
  23.      }
  24.   }
  25. }
  26.  
  27.  
  28. int main(){
  29.  
  30.     int x,y;
  31.  
  32.     while( cin >> x >> y ){
  33.     G[x][++G[x][0]] = y;
  34.     G[y][++G[y][0]] = x;
  35.     }
  36.  
  37.     BFS(1);
  38.  
  39.     for(int i=1; i<=10; i++ ) cout << i << " " << P[i] << endl;
  40.     /*for( int i=1; i<10; i++ ){
  41.         for( int j=0; j<10; j++ ){
  42.             cout << G[i][j] << "  ";
  43.         }
  44.         cout << endl;
  45.     }*/
  46.  
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment