Advertisement
Nevtr4l

BFS Algorithm

Jun 19th, 2025
589
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5.   // n: núm. de nodos - m: núm. de aristas
  6.   int n, m; cin >> n >> m;
  7.   vector<vector<int>> adj(n+1);
  8.   while (m--) {
  9.     int u, v; cin >> u >> v;
  10.     adj[u].push_back(v);
  11.     adj[v].push_back(u);
  12.   }
  13.  
  14.   vector<bool> vis(n+1);
  15.   queue<int> q;
  16.   function<void(int)> bfs = [&](int start) {
  17.     vis[start] = true;
  18.     q.push(start);
  19.  
  20.     while (!q.empty()) {
  21.       int u = q.front();
  22.       q.pop();
  23.       cout << u << ' ';
  24.  
  25.       for (int& v : adj[u]) {
  26.         if (vis[v]) continue;
  27.         vis[v] = true;
  28.         q.push(v);
  29.       }
  30.     }
  31.   };
  32.  
  33.   for (int u = 1; u <= n; u++) {
  34.     if (vis[u]) continue;
  35.     bfs(u);
  36.   }
  37.  
  38.   return 0;
  39. }
Tags: cpp
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement