Advertisement
WadeRollins2710

Depth-First Search Graph with Stack

Apr 12th, 2020
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. //Trần Việt Anh 19:25 12/04/2020
  2. #include<iostream>
  3. #include<fstream>
  4. #include<vector>
  5. #include<stack>
  6.  
  7. using namespace std;
  8.  
  9. vector<vector<int>> graph(0);
  10.  
  11. //Load the graph from text
  12. void LoadG() {
  13.     ifstream inFile;
  14.     inFile.open("dothi.txt");
  15.     int n; inFile >> n;
  16.     for (int i = 0; i < n; i++) {
  17.         vector<int> line(n);
  18.         for (int j = 0; j < n; j++)
  19.             inFile >> line[j];
  20.         graph.push_back(line);
  21.     }
  22. }
  23.  
  24. //Depth first search from starting node u (startNode)
  25. void DFS_Stack(int startNode) {
  26.     vector<int> visited(graph.size(), false);
  27.     stack<int> s;
  28.     s.push(startNode);
  29.     while (s.size() != 0) {
  30.         int node = s.top(); s.pop();
  31.         visited[node] = true;
  32.         cout << "Visited node " << node << endl;
  33.         for (int i = 0; i < graph.size(); i++)
  34.             if (graph[node][i] == 1 && !visited[i])
  35.                 s.push(i);
  36.     }
  37. }
  38.  
  39.  
  40. int main() {
  41.     LoadG();
  42.  
  43.     //Print the graph matrix for testing
  44.     for (int i = 0 ; i < graph.size(); i++) {
  45.         for (int j = 0; j < graph.size(); j++)
  46.             cout << graph[i][j] << " ";
  47.         cout << endl;
  48.     }
  49.  
  50.     //Depth first search
  51.     DFS_Stack(0);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement