STANAANDREY

dfs clasa

Jan 19th, 2021 (edited)
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. #define NMAX 30
  4. bool adjm[NMAX][NMAX], vis[NMAX];
  5. int n, m, start;
  6. int st[NMAX], top;
  7.  
  8. void read() {
  9.     cin >> n >> m >> start;
  10.     for (int i = 0; i < m; i++) {
  11.         int a, b;
  12.         cin >> a >> b;
  13.         adjm[a][b] = adjm[b][a] = true;
  14.     }
  15. }
  16.  
  17. void dfs(int p) {
  18.     vis[p] = true;
  19.     st[++top] = p;
  20.     for (int j = 1; j <= n; j++) {
  21.         if (adjm[p][j] && !vis[j]) {
  22.             dfs(j);
  23.         }
  24.     }
  25. }
  26.  
  27. void display() {
  28.     for (int i = 1; i <= top; i++)
  29.         cout << st[i] << ' ';
  30. }
  31.  
  32. int main() {
  33.     read();
  34.     dfs(start);
  35.     display();
  36.     return 0;
  37. }
  38.  
Add Comment
Please, Sign In to add comment