193030

BFS simple

Apr 15th, 2020
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. // Video - https://www.youtube.com/watch?v=J06Y4XKPQD8 <3
  2. #include<fstream>
  3. #include<queue>
  4. #include<vector>
  5. using namespace std;
  6.  
  7. // 9 10
  8. // 1 2
  9. // 3 4
  10. // 3 5
  11. // 4 6
  12. // 4 9
  13. // 9 8
  14. // 1 7
  15. // 7 3
  16. // 1 3
  17.  
  18. ifstream cin ("a.txt");
  19. ofstream cout ("a.out");
  20.  
  21. int main(){
  22.     int n,m;
  23.     int a,b;
  24.     cin>>n>>m; // n - nodes, m - arcs
  25.     vector <int> samp;
  26.     vector < vector <int> > conn(n+1,samp);
  27.     // load adajency matrix
  28.     for(int i=0;i<m;i++){
  29.         cin>>a>>b;
  30.         conn[a].push_back(b);
  31.         conn[b].push_back(a);
  32.     }
  33.     bool visited[n+1];
  34.     for(int i=0;i<n+1;i++){
  35.         visited[i] = false;
  36.     }
  37.     queue <int> level;
  38.     level.push(8);
  39.     visited[8] = true;
  40.     int si=0; // size
  41.     int le =0;
  42.     while(!level.empty()){
  43.         cout<<"LEVEL :"<<le<<endl;
  44.         si = level.size();
  45.         while(si--){
  46.             int x = level.front();
  47.             level.pop();
  48.             cout<<x<<endl;
  49.             for(int j=0;j<conn[x].size();j++){
  50.                 if(!visited[conn[x][j]]){
  51.                     visited[conn[x][j]] = true;
  52.                     level.push(conn[x][j]);
  53.                 }
  54.             }
  55.         }
  56.         le++;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment