Advertisement
nq1s788

BFS

Feb 15th, 2025
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3. #include <vector>
  4. #include <deque>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9.     int n, m;
  10.     cin >> n >> m;
  11.     vector < vector<int>>g(n);
  12.     int x, y;
  13.     for (int i = 0;i < m;i++)
  14.     {
  15.         cin >> x >> y;
  16.         g[x - 1].push_back(y - 1);
  17.         g[y - 1].push_back(x - 1);
  18.     }
  19.     deque<int> q;
  20.     vector<bool> used(n, false);
  21.     vector<int> answ(n, 0);
  22.     int start;
  23.     cin >> start;
  24.     start--;
  25.     q.push_back(start);
  26.     used[start] = true;
  27.     while (!q.empty()) {
  28.         int cur = q.front();
  29.         q.pop_front();
  30.         for (auto nxt : g[cur]) {
  31.             if (!used[nxt]) {
  32.                 answ[nxt] = answ[cur] + 1;
  33.                 used[nxt] = true;
  34.                 q.push_back(nxt);
  35.             }
  36.         }
  37.     }
  38.     for (auto e : answ) cout << e << ' ';
  39.     return 0;
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement