Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Parcurgerea in latime
- Breadth First Search
- */
- #include <fstream>
- using namespace std;
- ifstream fin("graf.in");
- ofstream fout("graf.out");
- const int MaxN = 101;
- bool a[MaxN][MaxN];
- bool s[MaxN]; // retine starea de vizitare a nodurilor
- int Q[MaxN];
- int p, u; // pozitia primului si a ultimului nod in coada
- int n;
- void ReadGraph();
- void Bf(int x);
- int main()
- {
- ReadGraph();
- Bf(1);
- fin.close();
- fout.close();
- }
- void Bf(int x)
- {
- p = 0, u = -1;
- Q[++u] = x; // nodul sursa se introduce in coada
- s[x] = true;
- fout << x << ' ';
- while (p <= u) // cat timp coada nu e vida
- {
- x = Q[p]; // aflam nodul din capul cozii
- p++; // "stergem" nodul din capul cozii
- for (int y = 1; y <= n; ++y)
- if (a[x][y] && !s[y]) // daca y e vecin nevizitat al lui x
- {
- Q[++u] = y; // y se introduce in coada
- s[y] = true; // se marcheaza
- fout << y << ' ';
- }
- }
- }
- void ReadGraph()
- {
- int x, y;
- fin >> n;
- while (fin >> x >> y)
- a[x][y] = a[y][x] = true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement