Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. //DFS
  2. #include<iostream>
  3. //#include<cstdlib>
  4. #include<stack>
  5. using namespace std;
  6. /*
  7. 8 7 1 5
  8. 1 2
  9. 1 3
  10. 2 3
  11. 2 4
  12. 3 5
  13. 4 6
  14. 7 8
  15. */
  16. stack <int> st;
  17. int n, m, dau, cuoi, *trace;
  18. bool **a, *s;
  19.  
  20. void nhap(){
  21.     cin>> n >> m >> dau >> cuoi;
  22.     dau--; cuoi--;
  23.     trace = new int [n];
  24.     s =  new bool [n];
  25.     a = new bool *[n];
  26.     for( int i = 0; i < n; i++) a [i] = new bool [n];
  27.     int u, v, i, j;
  28.     for(i = 0; i < n; i++){
  29.         s [i] = true;
  30.         for(j = 0; j < n; j++) a [i] [j] = false;
  31.     }
  32.     for(i = 0; i < m; i++){
  33.         cin>> u >> v;
  34.         u-- ; v--;
  35.         a [u][v] = true;
  36.         a [v][u] = true;
  37.     }
  38.     trace [dau] = -1;
  39. }
  40.  
  41. void DFS(){
  42.     int u, i, j = 1;
  43.     st.push(dau); s [dau] = false;
  44.     do{
  45.         u = st.top();
  46. //      if(u == cuoi) return;
  47.         for(i = 0; i < n; i++) if(s [i] && a [u][i]){
  48.             s [i] = false;
  49.             cout << i + 1 << " ";
  50.             st.push(i);
  51.             trace [i] = u;
  52.             break;
  53.         }
  54.         if(i >= n) st.pop();
  55.     }
  56.     while(!st.empty());
  57. }
  58. /*
  59. void res(){
  60.     if(st.empty()) return;
  61.     if(st.top() == dau){
  62.         cout<< st.top()+1 <<" ";
  63.         st.pop();
  64.         return ;
  65.     }
  66.     int u = st.top();
  67.     st.pop();
  68.     res();
  69.     cout<< u + 1 <<" ";
  70. }
  71. */
  72. void res(int i){
  73.     if(trace [i] >= 0) res(trace [i]);
  74.     cout<< i+1 <<" ";
  75. }                    
  76. int main(){
  77.     nhap();
  78.     cout << dau + 1 <<" can visit : " << dau + 1 << " ";
  79.     DFS();
  80.     cout<<endl;
  81.     res(cuoi);
  82.     delete []s;
  83.     for(int i = 0; i < n; i++) delete []a[i];
  84.     delete []a;
  85.     delete []trace;
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement