VasilM

DFS

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