Back to track
#33 Medium Intermediate

Graph BFS

Open the editor

Problem

Perform BFS traversal from a source.

Constraints

1 <= N, M <= 200000

Hints

  1. 1

    Use queue

  2. 2

    Mark visited

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n, m; cin >> n >> m;
  vector<vector<int>> g(n);
  for (int i = 0; i < m; i++) {
    int u, v; cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  int src; cin >> src;
  vector<int> vis(n, 0);
  queue<int> q;
  q.push(src);
  vis[src] = 1;
  vector<int> order;
  while (!q.empty()) {
    int u = q.front(); q.pop();
    order.push_back(u);
    for (int v : g[u]) if (!vis[v]) {
      vis[v] = 1; q.push(v);
    }
  }
  for (int i = 0; i < (int)order.size(); i++) {
    if (i) cout << ' ';
    cout << order[i];
  }
  cout << '\n';
  return 0;
}

© 2026 ChitChat