-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
47 lines (45 loc) · 1.03 KB
/
bfs.cpp
File metadata and controls
47 lines (45 loc) · 1.03 KB
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
47
#include <bits/stdc++.h>
using namespace std;
//Time Complexity O(V+E)
int main(){
vector<vector<int> > g;
int V,E;
cin>>V>>E;
g.resize(V+10);
for(int i=0;i<E;i++){
int u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
cout<<endl;
for(int i=1;i<=V;i++){
for(int j=0;j<g[i].size();j++) cout<<g[i][j]<<" ";
cout<<endl;
}
//BFS
cout<<endl;
vector<int> layer(V+5);
vector<bool> vis(V+5, false);
queue<int> Q;
int start;
cin>>start;
layer[start]=0;
Q.push(start);
vis[start]=true;
while(!Q.empty()){
int u=Q.front();
Q.pop();
for(int i=0;i<g[u].size();i++){
int v=g[u][i];
if(!vis[v]){
Q.push(v);
layer[v]=layer[u]+1;
vis[v]=true;
}
}
}
for(int i=1;i<=V;i++) if(vis[i]) cout<<i<<" ";
//For an unweighted graph, layer[u] also gives the shortest distance of vertex u from start
return 0;
}