Untitled
unknown
plain_text
a year ago
753 B
5
Indexable
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
void bfs(vector<vector<int>> &G, int s) {
vector<bool> visited(G.size(), false);
queue<int> q;
q.push(s);
visited[s] = true;
while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";
for (int neighbor : G[node]) {
if (!visited[neighbor]) {
q.push(neighbor);
visited[neighbor] = true;
}
}
}
}
int main() {
int e,x,y;
cin>>e;
vector<vector<int>> G(e);
for(int i=0; i<e;i++){
cin>>x>>y;
G[x].push_back(y);
G[y].push_back(x);
}
bfs(G, 0);
return 0;
}Editor is loading...
Leave a Comment