BFS
unknown
c_cpp
a year ago
662 B
35
Indexable
#include <bits/stdc++.h>
using namespace std;
set<int>adj[101];
vector<bool>v(101, false);
void bfs(int u) {
queue<int>q; q.push(u); v[u] = true;
while (!q.empty()) {
int cur = q.front(); q.pop();
cout << cur << endl;
for (int j : adj[cur]) {
if (!v[j]) {
q.push(j);
v[j] = true;
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m; cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v; cin >> u >> v;
adj[u].insert(v);
adj[v].insert(u);
}
bfs(1);
}Editor is loading...
Leave a Comment