Advertisement
STRWBRRKNG

DFS (Depth-first search)

Feb 19th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <stack>
  5. #include <map>
  6. #include <set>
  7. #include <algorithm>
  8. #include <unordered_map>
  9. #include <set>
  10. #include <unordered_set>
  11.  
  12. using namespace std;
  13.  
  14. void DFS(vector<vector<int>>& djacencyMatrix, int startVertex) {  // a Depth-first search
  15.   stack<int> q;
  16.   q.push(startVertex);
  17.   while (!q.empty()) {
  18.     auto a = q.top();
  19.     cout << a << endl;
  20.     q.pop();
  21.     for (int i = 0; i < djacencyMatrix.size(); i++) {
  22.       if (djacencyMatrix[a][i] == 1) {
  23.         q.push(i);
  24.       }
  25.     }
  26.   }
  27. }
  28.  
  29. int main()
  30. {
  31.   size_t vrtcsN = 9;
  32.  
  33.   vector<vector<int>> adjacencyMatrix(vrtcsN, std::vector<int>(vrtcsN));
  34.  
  35.   adjacencyMatrix[0][1] = 1;
  36.   adjacencyMatrix[0][2] = 1;
  37.   adjacencyMatrix[1][3] = 1;
  38.   adjacencyMatrix[1][4] = 1;
  39.   adjacencyMatrix[1][5] = 1;
  40.   adjacencyMatrix[2][6] = 1;
  41.   adjacencyMatrix[2][7] = 1;
  42.   adjacencyMatrix[7][8] = 1;
  43.  
  44.   /*   EXAMPLE TREE:       (it's guaranteed that there are no cycles in example)          
  45.             0
  46.           /   \
  47.         1       2
  48.       / | \    /  \
  49.      3  4  5   6   7
  50.                    |
  51.                    8  
  52.   */
  53.  
  54.   DFS(adjacencyMatrix, 0);
  55.  
  56.   // *result*: 0 2 7 8 6 1 5 4 3
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement