Advertisement
tuttelikz

DFS - Depth First Search [+]

Feb 8th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <math.h>
  7. #include <string>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <string>
  11. #include <stdlib.h>
  12. #include <cmath>
  13. #include <iomanip>
  14.  
  15. using namespace std;
  16. #define N 100
  17.  
  18. int g[N][N];
  19. bool visited[N];
  20. int n, s;
  21. vector <int> d;
  22.  
  23. void dfs (int u) {
  24.     d.push_back(u); //remember path
  25.     visited[u] = true;  //put visited immediately
  26.     for (int i = 1; i <= n; i++) {
  27.         if (!visited[i] && g[u][i] == 1) {  //if next is not visited & there is a way between
  28.             dfs (i);    //dfs again
  29.         }
  30.     }
  31. }
  32.  
  33. int main(int argc, const char * argv[]) {
  34.     cin >> n >> s;  //take size and starting point
  35.     for (int i = 1; i <= n; i++) {
  36.         for (int j = 1; j <= n; j++) {
  37.             cin >> g[i][j];     //input matrix
  38.         }
  39.     }
  40.     dfs (s);    //start dfs
  41.     for (int i = 0; i < n; i++) {
  42.         cout << d[i] << " ";    //output path
  43.     }
  44.     cout << endl;
  45.    
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement