-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.CPP
More file actions
70 lines (64 loc) · 846 Bytes
/
BFS.CPP
File metadata and controls
70 lines (64 loc) · 846 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream.h>
#include<conio.h>
class reach
{
int n,s[20],a[20][20],src;
public: void bfs();
void read();
void print();
};
void reach::read()
{
cout<<"\n enter no. of nodes \n";
cin>>n;
cout<<"\n enter adjacency matrix\n";
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<"enter the source\n";
cin>>src;
}
void reach::print()
{
for(int i=0;i<n;i++)
{
if(s[i]==0)
cout<<" vertex "<<i<<" is not reachable\n";
else
cout<<" vertex "<<i<<" is reachable\n";
}
}
void reach::bfs()
{
int f,r,q[20],u,v,i;
for(i=1;i<=n;i++)
s[i]=0;
f=r=0;
q[r]=src;
s[src]=1;
while(f<=r)
{
u=q[f++];
for(v=1;v<=n;v++)
{
if(a[u][v]==1&&s[v]==0)
{
s[v]=1;
q[++r]=v;
}
}
}
}
void main()
{
clrscr();
reach a;
a.read();
a.bfs();
a.print();
getch();
}