Advertisement
RaresDumitrica

Lab 6 - Graph Kruskacl

Jan 17th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. class Graph
  7. {
  8. private:
  9.     int nrNodes;
  10.     int matrix[100][100];
  11.     int viz[100];
  12.     int queue[100];
  13.  
  14. public:
  15.     Graph()
  16.     {
  17.         nrNodes = 100;
  18.         for (int i = 1; i <= nrNodes; i++)
  19.         {
  20.             viz[i] = 0;
  21.             queue[i] = 0;
  22.             for(int j = 1; j <= nrNodes; j++)
  23.                 matrix[i][j] = 0;
  24.         }
  25.  
  26.     }
  27.     void reinit()
  28.     {
  29.         for(int i = 1; i<= nrNodes; i++)
  30.             viz[i] = 0;
  31.     }
  32.     void readGraph();
  33.     void DFS(int current);
  34.     void BFS(int start);
  35. };
  36.  
  37. void Graph::readGraph()
  38. {
  39.     int firstNode, secondNode;
  40.     ifstream f("input.txt");
  41.     int nrOfEdges;
  42.     f>>nrOfEdges;
  43.     f>>nrNodes;
  44.     for(int i = 1; i <= nrOfEdges; i++)
  45.     {
  46.         f>>firstNode>>secondNode;
  47.         matrix[firstNode][secondNode] = matrix[secondNode][firstNode] = 1;
  48.     }
  49.     f.close();
  50. }
  51.  
  52. void Graph::DFS(int current)
  53. {
  54.     if (viz[current] == 1)
  55.         return;
  56.  
  57.     viz[current] = 1;
  58.  
  59.     cout<<current<<' ';
  60.  
  61.     for (int i = 1; i <= nrNodes; i++)
  62.         if(matrix[current][i] == 1)
  63.             DFS(i);
  64. }
  65.  
  66. void Graph::BFS(int start)
  67. {
  68.     queue[1] = start;
  69.     viz[start] = 1;
  70.     int p = 1, u = 1;
  71.     int current;
  72.  
  73.     while (p <= u)//coada nevida
  74.     {
  75.         current = queue[p];
  76.         p++;
  77.         cout<<current<<' ';
  78.         for (int i = 1; i <= nrNodes; i++)
  79.             if (matrix[current][i] == 1 && viz[i] == 0)
  80.             {
  81.                 u++;
  82.                 queue[u] = i;
  83.                 viz[i] = 1;
  84.             }
  85.     }
  86. }
  87.  
  88. int main()
  89. {
  90.     Graph g;
  91.     g.readGraph();
  92.     cout<<"DFS: ";
  93.     g.DFS(1);
  94.     cout<<endl;
  95.     g.reinit();
  96.     cout<<"BFS: ";
  97.     g.BFS(1);
  98.  
  99.     return 0;
  100. }
  101.  
  102.  
  103. INPUT:
  104. 6 6
  105. 1 2
  106. 1 5
  107. 2 3
  108. 2 4
  109. 3 4
  110. 3 6
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement