Advertisement
kazi_omar

dfs

Mar 11th, 2021
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4.  
  5. vector<int> v[100];
  6. int vis[100] = {0};
  7. vector<int> v1;
  8.  
  9. void dfs(int x)
  10. {
  11.     v1.push_back(x);
  12.     cout << x << ": " << endl;
  13.     int s = v[x].size();
  14.     vis[x] = 1;
  15.     for (int i = 0; i < s; i++)
  16.     {
  17.         if (!vis[v[x][i]])
  18.         {
  19.             dfs(v[x][i]);
  20.             v1.push_back(x);
  21.             cout << "return to callee:  " << x
  22.                  << endl;
  23.         }
  24.     }
  25. }
  26.  
  27. // void dfs(int at)
  28. // {
  29. //     if (vis[at])
  30. //         return;
  31. //     vis[at] = 1;
  32. //     v1.push_back(at);
  33. //     for (int i = 0; i < v[at].size(); i++)
  34. //     {
  35. //         if (!vis[v[at][i]])
  36. //         {
  37. //             //cout << v[at][i] << " ";
  38. //             dfs(v[at][i]);
  39. //             v1.push_back(at);
  40. //         }
  41. //     }
  42. //     //cout << endl;
  43. // }
  44.  
  45. int main()
  46. {
  47.     int node, edge;
  48.     cout << "all adjacent path from source 1 --> destination: " << endl;
  49.     cin >> node >> edge;
  50.  
  51.     int s, d;
  52.     for (int i = 0; i < edge; i++)
  53.     {
  54.         cin >> s >> d;
  55.         v[s].push_back(d);
  56.         v[d].push_back(s);
  57.     }
  58.  
  59.     for (int i = 1; i <= node; i++)
  60.     {
  61.         cout << i << "--> ";
  62.         for (int j = 0; j < v[i].size(); j++)
  63.         {
  64.             cout << v[i][j] << " ";
  65.         }
  66.         cout << endl;
  67.     }
  68.     cout << endl;
  69.  
  70.     dfs(1);
  71.     cout << "final adj path: " << endl;
  72.     auto itr = v1.begin();
  73.     for (; itr != v1.end(); itr++)
  74.     {
  75.         cout << *itr << " ";
  76.     }
  77.  
  78.     return 0;
  79. }
  80.  
  81. // 8 9
  82. // 1 3
  83. // 1 4
  84. // 2 5
  85. // 2 6
  86. // 3 4
  87. // 4 5
  88. // 6 6
  89. // 5 7
  90. // 7 7
  91.  
  92. // 1 7
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement