-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBreath First Search.cpp
55 lines (52 loc) · 1.1 KB
/
Breath First Search.cpp
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
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
vector< int > adj[100];
bool visited[100];
int n,e,u,v,x,y;
void BFS(int source)
{
int i;
queue< int > queue;
memset(visited,false, sizeof(visited));
queue.push(source);
visited[source] = 2;
while(!queue.empty())
{
u = queue.front();
queue.pop();
cout<<u<<"->";
visited[u] = true;
for(i=0;i< adj[u].size();i++)
{
v = adj[u][i];
if(visited[v]==false)
{
queue.push(v);
visited[v] = 2;
}
}
}
}
int main()
{
int source;
cout<<"Enter number of vertices: ";
cin>>n;
cout<<"Enter number of edges: ";
cin>>e;
memset(adj,false,sizeof(adj));
cout<<"Enter vertex to vertex"<<endl;
while(e--)
{
cin>>x>>y;
adj[x].push_back(y);
adj[y].push_back(x);
}
cout<<"Enter the source to start the BFS traversal: ";
cin>>source;
BFS(source);
return 0;
}