Advertisement
Guest User

Depth First Search

a guest
Apr 22nd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <cstring>
  4. #include <algorithm>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. int n, m, cnt = 0, a, b, v, arr[101][101], lamps[101];
  10.  
  11. void dfs(int v)
  12. {
  13.     lamps[v] = 1;
  14.     cout << v + 1 << " ";
  15.    
  16.     for (int i = 0; i < n; i++)
  17.     {
  18.         if(arr[v][i] == 1 && lamps[i] == 0)
  19.         {
  20.             dfs(i);
  21.         }
  22.     }
  23. }
  24.  
  25. int main()
  26. {
  27.     //--------------------------------
  28.     ios_base::sync_with_stdio(false);
  29.     cin.tie(0);
  30.     cout.tie(0);
  31.     //--------------------------------
  32.    
  33.     cin >> n >> m;
  34.    
  35.     for (int i = 0; i < m; i++)
  36.     {
  37.         cin >> a >> b;
  38.         arr[a-1][b-1] = arr[b-1][a-1] = 1;
  39.     }
  40.    
  41.     cin >> v;
  42.    
  43.     dfs(v-1);
  44.    
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement