SHARE
TWEET

BFS using STL

albnayem Jun 20th, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3.     Author: Abdullah Al Nayem
  4.     Leading University, Sylhet.
  5. */
  6.  
  7. #include <bits/stdc++.h>
  8. #define pb push_back
  9.  
  10. using namespace std;
  11.  
  12. vector<bool> v;
  13. vector<vector<int> > g;
  14.  
  15.  
  16. void bfs(int startingNode)
  17. {
  18.     queue<int> q;
  19.  
  20.     q.push(startingNode);
  21.     v[startingNode] = true;
  22.  
  23.     while (!q.empty()) {
  24.  
  25.         int x = q.front();
  26.         q.pop();
  27.  
  28.         cout << x << " ";
  29.  
  30.         for (int i = g[x][0]; i<g[x].size(); i++) {
  31.             if (!v[i]) {
  32.                 q.push(i);
  33.                 v[i] = true;
  34.             }
  35.         }
  36.     }
  37. }
  38.  
  39. int main()
  40. {
  41.     int n, e;
  42.     cin >> n >> e;
  43.  
  44.     v.assign(n, false);
  45.     g.assign(n, vector<int>());
  46.  
  47.     int a, b;
  48.     for (int i = 0; i < e; i++) {
  49.         cin >> a >> b;
  50.         g[a].pb(b);
  51.         g[b].pb(a);
  52.     }
  53.  
  54.     for (int i = 0; i < n; i++) {
  55.         if (!v[i])
  56.             bfs(i);
  57.     }
  58.  
  59.     return 0;
  60. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top