Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- #include <stack>
- #include <map>
- #include <set>
- #include <algorithm>
- #include <unordered_map>
- #include <set>
- #include <unordered_set>
- using namespace std;
- void DFS(vector<vector<int>>& djacencyMatrix, int startVertex) { // a Depth-first search
- stack<int> q;
- q.push(startVertex);
- while (!q.empty()) {
- auto a = q.top();
- cout << a << endl;
- q.pop();
- for (int i = 0; i < djacencyMatrix.size(); i++) {
- if (djacencyMatrix[a][i] == 1) {
- q.push(i);
- }
- }
- }
- }
- int main()
- {
- size_t vrtcsN = 9;
- vector<vector<int>> adjacencyMatrix(vrtcsN, std::vector<int>(vrtcsN));
- adjacencyMatrix[0][1] = 1;
- adjacencyMatrix[0][2] = 1;
- adjacencyMatrix[1][3] = 1;
- adjacencyMatrix[1][4] = 1;
- adjacencyMatrix[1][5] = 1;
- adjacencyMatrix[2][6] = 1;
- adjacencyMatrix[2][7] = 1;
- adjacencyMatrix[7][8] = 1;
- /* EXAMPLE TREE: (it's guaranteed that there are no cycles in example)
- 0
- / \
- 1 2
- / | \ / \
- 3 4 5 6 7
- |
- 8
- */
- DFS(adjacencyMatrix, 0);
- // *result*: 0 2 7 8 6 1 5 4 3
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement