-
Notifications
You must be signed in to change notification settings - Fork 0
/
5b_BFS.cpp
53 lines (47 loc) · 922 Bytes
/
5b_BFS.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
#include <iostream>
using namespace std;
int q[20],f=0,r=-1;
int a[50][50],visited[50],n,s;;
void BFS(int k)
{
int w;
visited[k]=1;
r++;
q[r]=k;
cout<<"The breadth first order is:\n";
while(f<=r)
{
w=q[f];
f++;
cout<<w<<" ";
for(int i=1;i<=n;i++)
{
if(a[w][i]==1 && visited[i]==0)
{
r++;
q[r]=i;
visited[i]=1;
}
}
}
}
int main()
{
cout << "Enter the number of vertices in the graph :\n ";
cin>>n;
cout<<"Enter the adjacency matrix : "<<endl;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>a[i][j];
}
cout<<endl;
}
for(int i=0;i<n;i++)
visited[i]=0;
cout<<"Enter the source vertex :\n ";
cin>>s;
BFS(s);
return 0;
}