Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- void bfs(vector<vector<int> > &adj){
- vector<int> visited(adj.size(), false);
- queue<int> q;
- int source = 1;
- q.push(source);
- visited[source] = true;
- while(!q.empty()){
- //take out the front node in queue
- int front = q.front();
- //pop the front
- q.pop();
- //print
- cout << front << " ";
- for(int i = 0; i < adj[front].size(); i++){
- int node = adj[front][i];
- if(!visited[node]){
- q.push(node);
- visited[node] = true;
- }
- }
- }
- }
- int main() {
- // your code goes here
- int n, m;
- cin >> n >> m;
- vector<vector<int> > adj(n + 1, vector<int>());
- for(int i = 0; i < m; i++){
- int u, v;
- cin >> u >> v;
- adj[u].push_back(v);
- adj[v].push_back(u);
- }
- bfs(adj);
- }
Advertisement
Add Comment
Please, Sign In to add comment