Advertisement
icatalin

ASD Grafuri

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