-
Notifications
You must be signed in to change notification settings - Fork 2
/
BREADTH_FIRST_SEARCH.cpp
52 lines (52 loc) · 926 Bytes
/
BREADTH_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
//Breadth First Search
#include<iostream.h>
#include<conio.h>
class BGraph
{
int a[10][10], n, start;
public:
void getdata();
void bfs_traverse();
};
void BGraph::getdata()
{
cout<<"\n Enter the number of vertices in the graph: ";
cin>>n;
cout<<"\n Enter the adjacency matrix of graph: "<<endl;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
cout<<"\n Enter the vertex from which you want to traverse: ";
cin>>start;
}
void BGraph::bfs_traverse()
{
int *visited= new int[n];
int queue[10], front= -1, rear=0, i;
for(int j=0;j<n;j++)
visited[j]=0;
cout<<"\n Traversing the graph using breadth first search algorithm : "<<endl;
queue[rear]=start;
visited[start]=1;
while(front!=rear)
{
cout<<queue[++front]<<endl;
i=queue[front];
for(int j=0;j<n;j++)
{
if(a[i][j]!=0 && visited[j]!=1)
{
queue[++rear]=j;
visited[j]=1;
}
}
}
}
int main()
{
BGraph bfs;
bfs.getdata();
bfs.bfs_traverse();
getch();
return 0;
}