Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. /* Parcurgerea in latime
  2. Breadth First Search
  3. */
  4. #include <fstream>
  5. using namespace std;
  6.  
  7. ifstream fin("graf.in");
  8. ofstream fout("graf.out");
  9.  
  10. const int MaxN = 101;
  11. bool a[MaxN][MaxN];
  12. bool s[MaxN]; // retine starea de vizitare a nodurilor
  13. int Q[MaxN];
  14. int p, u; // pozitia primului si a ultimului nod in coada
  15. int n;
  16.  
  17. void ReadGraph();
  18. void Bf(int x);
  19.  
  20. int main()
  21. {
  22. ReadGraph();
  23. Bf(1);
  24. fin.close();
  25. fout.close();
  26. }
  27.  
  28. void Bf(int x)
  29. {
  30. p = 0, u = -1;
  31. Q[++u] = x; // nodul sursa se introduce in coada
  32. s[x] = true;
  33. fout << x << ' ';
  34.  
  35. while (p <= u) // cat timp coada nu e vida
  36. {
  37. x = Q[p]; // aflam nodul din capul cozii
  38. p++; // "stergem" nodul din capul cozii
  39.  
  40. for (int y = 1; y <= n; ++y)
  41. if (a[x][y] && !s[y]) // daca y e vecin nevizitat al lui x
  42. {
  43. Q[++u] = y; // y se introduce in coada
  44. s[y] = true; // se marcheaza
  45. fout << y << ' ';
  46. }
  47. }
  48. }
  49.  
  50. void ReadGraph()
  51. {
  52. int x, y;
  53. fin >> n;
  54. while (fin >> x >> y)
  55. a[x][y] = a[y][x] = true;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement