-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
78 lines (72 loc) · 1.54 KB
/
Copy pathBFS.cpp
File metadata and controls
78 lines (72 loc) · 1.54 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
74
75
76
77
78
#include <iostream>
#include <stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,qu[10],front,rear,v,visit[10],visited[10];
int stk[10], top, visit1[10], visited1[10];
int main()
{
int m;
cout<<"Enter number of vertices : ";
cin>>n;
cout<<"Enter number of edges : ";
cin>>m;
cout<<"\nEDGES :\n";
for(k=1;k<=m;k++)
{
cin>>i>>j;
cost[i][j]=1;
cost[j][i]=1;
}
//display function
cout<<"The adjacency matrix of the graph is : "<<endl;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<" " <<cost[i][j];
}
cout<<endl;
}
cout<<"Enter initial vertex : ";
cin>>v;
cout<<"The BFS of the Graph is\n";
cout<<v<<endl;
visited[v]=1;
k=1;
while (k<n)
{
for(j=1;j<=n;j++)
if (cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
qu[rear++]=j;
}
v=qu[front++];
cout<<v<<" ";
k++;
visit[v]=0;
visited[v]=1;
}
cout<<endl<<"Enter initial vertex : ";
cin>>v;
cout<<"The DFS of the Graph is\n";
cout<<v<<endl;
visited[v]=1;
k=1;
while(k<n)
{
for(j=n;j>=1;j--)
if(cost[v][j]!=0 && visited1[j]!=1 && visit1[j]!=1)
{
visit1[j]=1;
stk[top]=j;
top++;
}
v=stk[--top];
cout<<v<<" ";
k++;
visit1[v]=0;
visited1[v]=1;
}
return 0;
}