-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFS.cpp
More file actions
46 lines (40 loc) · 905 Bytes
/
BFS.cpp
File metadata and controls
46 lines (40 loc) · 905 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void BFS(int v, map<int,set<int>> adj){
map<int,bool> visit;
vector<int> ans;
for(int i=0;i<v;i++){
if(!visit[i]){
queue<int> q;
q.push(i);
visit[i]=1;
while(!q.empty()){
int frontend=q.front();
q.pop();
ans.push_back(frontend);
for(int it: adj[frontend]){
if(!visit[it]){
ans.push_back(it);
visit[it]=1;
}
}
}
}
}
for(auto i: ans){
cout<<i<<",";
}
}
int main(){
int n,m;
cin>>n>>m;
map<int, set<int>> adj;
for(int i=0;i<m;i++){
int u,v;
cin>>u>>v;
adj[u].insert(v);
}
BFS(n, adj);
return 0;
}