Advertisement
jasonpogi1669

Simple BFS Traversal using C++

May 18th, 2021
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. /**
  6.  
  7.     Use this as input: (copy-paste in terminal)
  8.    
  9.     3
  10.     4 2
  11.     1 2
  12.     2 3
  13.     5 3
  14.     1 2
  15.     2 3
  16.     1 3
  17.     6 3
  18.     1 2
  19.     3 4
  20.     5 6
  21.  
  22. */
  23.  
  24. vector<vector<int>> a;
  25. vector<bool> visited;
  26. int cnt = 0;
  27.  
  28. void BFS(int u) {
  29.     queue<int> q;
  30.     visited[u] = true;
  31.     q.push(u);
  32.     while (!q.empty()) {
  33.         u = q.front();
  34.         q.pop();
  35.         for (auto it = a[u].begin(); it != a[u].end(); it++) {
  36.             if (!visited[*it]) {
  37.                 visited[*it] = true;
  38.                 q.push(*it);
  39.                 cout << " -> " << *it + 1;
  40.             }
  41.         }
  42.     }
  43. }
  44.  
  45. int main() {
  46.     int tt;
  47.     cin >> tt;
  48.     while (tt--) {
  49.         int n, m;
  50.         cin >> n >> m;
  51.         a = vector<vector<int>>(n);
  52.         for (int i = 0; i < m; i++) {
  53.             int u, v;
  54.             cin >> u >> v;
  55.             --u, --v;
  56.             a[u].push_back(v);
  57.             a[v].push_back(u);
  58.         }
  59.         visited = vector<bool>(n, false);
  60.         for (int u = 0; u < n; u++) {
  61.             if (!visited[u]) {
  62.                 cout << u + 1;
  63.                 BFS(u);
  64.                 cout << '\n';
  65.             }
  66.         }
  67.         cout << "----\n";
  68.     }
  69.     return 0;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement