Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Trần Việt Anh 19:25 12/04/2020
- #include<iostream>
- #include<fstream>
- #include<vector>
- #include<stack>
- using namespace std;
- vector<vector<int>> graph(0);
- //Load the graph from text
- void LoadG() {
- ifstream inFile;
- inFile.open("dothi.txt");
- int n; inFile >> n;
- for (int i = 0; i < n; i++) {
- vector<int> line(n);
- for (int j = 0; j < n; j++)
- inFile >> line[j];
- graph.push_back(line);
- }
- }
- //Depth first search from starting node u (startNode)
- void DFS_Stack(int startNode) {
- vector<int> visited(graph.size(), false);
- stack<int> s;
- s.push(startNode);
- while (s.size() != 0) {
- int node = s.top(); s.pop();
- visited[node] = true;
- cout << "Visited node " << node << endl;
- for (int i = 0; i < graph.size(); i++)
- if (graph[node][i] == 1 && !visited[i])
- s.push(i);
- }
- }
- int main() {
- LoadG();
- //Print the graph matrix for testing
- for (int i = 0 ; i < graph.size(); i++) {
- for (int j = 0; j < graph.size(); j++)
- cout << graph[i][j] << " ";
- cout << endl;
- }
- //Depth first search
- DFS_Stack(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement