Advertisement
monyca98

bfs dfs iterativ

May 25th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<vector>
  4. #include<queue>
  5. #define MAX_SIZE 100
  6. typedef std::vector<int> graph;
  7.  
  8. void read_from_file(graph G[], int &source)
  9. {
  10. std::ifstream in("file_bfs_dfs.txt");
  11. if (!in.is_open())
  12. std::cout << "The file wasn't opened!\n";
  13. else
  14. {
  15. int n; //nr de noduri
  16. in >> n;
  17. in >> source;
  18. int x, y; //extremitatile fiecarei muchii
  19. while (in >> x >> y)
  20. {
  21. G[x].push_back(y);
  22. G[y].push_back(x);
  23. }
  24.  
  25. }
  26.  
  27. }
  28.  
  29. void bfs(graph G[], int source)
  30. {
  31. std::queue<int> Q;
  32. Q.push(source);
  33. std::vector<int> visited(MAX_SIZE,0);
  34. visited[source] = 1;
  35.  
  36. while (!Q.empty())
  37. {
  38. int v_curent = Q.front();
  39. Q.pop();
  40. std::cout << v_curent <<" ";
  41. for (int i = 0; i < G[v_curent].size(); i++)
  42. {
  43. if (!visited[G[v_curent][i]])
  44. {
  45. visited[G[v_curent][i]] = 1;
  46. Q.push(G[v_curent][i]);
  47. }
  48. }
  49. }
  50. std::cout << std::endl;
  51. }
  52.  
  53. std::vector<bool> vis_dfs(MAX_SIZE, 0);
  54. #include<stack>
  55. void dfs (int source)
  56. {
  57. std::stack<int> S;
  58. S.push(source);
  59. while (!S.empty())
  60. {
  61. int curent = S.top();
  62. S.pop();
  63.  
  64. if (!vis_dfs[curent])
  65. {
  66. vis_dfs[curent] = 1;
  67. //std::cout << curent << " ";
  68. for (int i = 0; i < g[curent].size(); i++)
  69. {
  70. if (g[curent][i]==1 && !vis_dfs[i])
  71. S.push(i);
  72. }
  73. }
  74. }
  75. //std::cout << std::endl;
  76. }
  77.  
  78. int main()
  79. {
  80. graph G[MAX_SIZE];
  81. int source;
  82. read_from_file(G,source);
  83. std::cout << "----BFS----\n";
  84. bfs(G,source);
  85.  
  86. std::cout << "-----DFS-----\n";
  87. dfs(G, source);
  88. return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement