Advertisement
ainem

DFS

Aug 14th, 2021
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. /*    Never let anyone dull your sparkle...    */
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // type definition
  6. #define int long long
  7. using i64 = int64_t;
  8. typedef pair<int, int> ii;
  9. // constants
  10. constexpr int N = 2e6 + 2;
  11. constexpr int INF = 0x3f3f3f3f;
  12. constexpr int MOD = 1e9 + 7;
  13. constexpr float PI = 3.14;
  14. // possible moves
  15. constexpr int dx[8] = {1, 1, -1, -1, 0, 0, 1, -1};
  16. constexpr int dy[8] = {1, 0, -1, 0, 1, -1, -1, 1};
  17. // shortcuts
  18. #define pb push_back
  19. #define eb emplace_back
  20. #define mp make_pair
  21. #define fi first
  22. #define se second
  23. #define endl '\n'
  24. #define sz(x) i64(x.size())
  25. #define all(x) begin(x), end(x)
  26. #define rall(x) begin(x), end(x), greater<int>()
  27. // loop definition
  28. #define FOR(i, n, m) for (int i = n; i <= m; ++i)
  29. #define FORD(i, n, m) for (int i = n; i >= m; --i)
  30.  
  31. int n, m, s, t;
  32. vector<int> g[N];
  33. bool visited[N];
  34. int parent[N];
  35. void DFS(int u) {
  36.     visited[u] = true;
  37.  
  38.     for (auto v : g[u]) {
  39.         if (!visited[v]) {
  40.             parent[v] = u;
  41.             DFS(v);
  42.         }
  43.     }
  44. }
  45. void print_path() {
  46.     if (!visited[t]) {
  47.         cout << "No path!";
  48.     }
  49.     else {
  50.         vector<int> path;
  51.         while (t != s) {
  52.             path.pb(t);
  53.             t = parent[t];
  54.         }  
  55.         path.pb(s);
  56.         reverse(all(path));
  57.         for (auto i : path) cout << i << ' ';
  58.     }
  59. }
  60. int32_t main(void) {
  61.     ios_base::sync_with_stdio(false);
  62.     cin.tie(nullptr);
  63.  
  64.     //freopen("main.INP", "r", stdin);
  65.     //freopen("main.OUT", "w", stdout);
  66.  
  67.     cin >> n >> m >> s >> t;
  68.     while (m--) {
  69.         int x, y;
  70.         cin >> x >> y;
  71.         g[x].pb(y);
  72.         g[y].pb(x);
  73.     }
  74.  
  75.     DFS(s);
  76.     print_path();
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement