SHARE
TWEET

BFS

shabbyheart Jun 16th, 2019 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #include<iostream>
  4. queue<int>que;
  5. bool visited[100];
  6. vector<int>adj[50];
  7. void bfs(int src)
  8. {
  9.     que.push(src);
  10.     visited[src]=true;
  11.     cout<<src<<" ";
  12.     while(!que.empty())
  13.     {
  14.         int parent=que.front();
  15.         que.pop();
  16.         for(int i=0;i<adj[parent].size();i++)
  17.         {
  18.             int child=adj[parent][i];
  19.             if(visited[child]==0)
  20.             {
  21.                 que.push(child);
  22.                 visited[child]=true;
  23.                 cout<<child<<" ";
  24.             }
  25.         }
  26.     }
  27. }
  28.  
  29. int main()
  30. {
  31.     int node,edge,m,n;
  32.     cin>>node>>edge;
  33.  
  34.     while(edge--)
  35.     {
  36.         cin>>m>>n;
  37.         adj[m].push_back(n);
  38.         adj[n].push_back(m);
  39.     }
  40.     bfs(1);
  41.  
  42. }
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