-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
73 lines (56 loc) · 1.02 KB
/
BFS.cpp
File metadata and controls
73 lines (56 loc) · 1.02 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
In this code node start with 0.
node=7 ,edges = 6
So given input is
0 1
0 2
1 3
1 4
2 5
2 6
*/
#include<bits/stdc++.h>
#define pb push_back
#define t true
#define f false
using namespace std;
vector<bool>v;
vector<vector<int> >g;
void BFS(int s)
{
queue<int>q;
q.push(s);
v[s] = t;
while(!q.empty()){
int u = q.front();
q.pop();
cout<<u<<" ";
for(int i=0 ; i<g[u].size() ; i++){
if(!v[g[u][i]]){
int k = g[u][i];
v[k] = t;
q.push(k);
}
}
}
}
int main()
{
int n,e;
cout<<"Enter the number of nodes :";
cin>>n;
cout<<"Enter the number of edges :";
cin>>e;
v.assign(n,f);
g.assign(n,vector<int> ());
int n1,n2,s;
for(int i=0 ; i<e ; i++){
cin>>n1>>n2;
g[n1].pb(n2);
g[n2].pb(n1);
}
cout<<"Enter the starting node : ";
cin>>s;
BFS(s);
return 0;
}