Fastrail08

BFS

Aug 4th, 2025
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void bfs(vector<vector<int> > &adj){
  5.     vector<int> visited(adj.size(), false);
  6.     queue<int> q;
  7.    
  8.     int source = 1;
  9.     q.push(source);
  10.     visited[source] = true;
  11.    
  12.     while(!q.empty()){
  13.         //take out the front node in queue
  14.         int front = q.front();
  15.        
  16.         //pop the front
  17.         q.pop();
  18.        
  19.         //print
  20.         cout << front << " ";
  21.        
  22.         for(int i = 0; i < adj[front].size(); i++){
  23.             int node = adj[front][i];
  24.             if(!visited[node]){
  25.                 q.push(node);
  26.                 visited[node] = true;
  27.             }
  28.         }
  29.        
  30.     }
  31. }
  32.  
  33. int main() {
  34.     // your code goes here
  35.     int n, m;
  36.     cin >> n >> m;
  37.    
  38.    vector<vector<int> > adj(n + 1, vector<int>());
  39.    
  40.    for(int i = 0; i < m; i++){
  41.        int u, v;
  42.        cin >> u >> v;
  43.        adj[u].push_back(v);
  44.        adj[v].push_back(u);
  45.    }
  46.    
  47.    bfs(adj);
  48.    
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment