forked from spandey1296/CODEMONK-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraverbfs.C
140 lines (124 loc) Β· 2.27 KB
/
traverbfs.C
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/* Program for traversing a graph through BFS */
/* Data Structures Using C by UDIT AGARWAL */
#include<stdio.h>
#include<conio.h>
#define MAX 20
typedef enum boolean{false,true} bool;
int adj[MAX][MAX];
bool visited[MAX];
int n;
void main()
{
int i,v,choice;
clrscr();
printf("\n\tTraversing of a graph through BFS\n");
printf("\t**********************************\n\n");
create_graph();
while(1)
{
printf("\n");
printf("1. Adjacency matrix\n");
printf("2. Breadth First Search\n");
printf("3. Adjacent vertices\n");
printf("4. Exit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Adjacency Matrix\n");
display();
break;
case 2:
printf("Enter starting node for Breadth First Search : ");
scanf("%d", &v);
for(i=1;i<=n;i++)
visited[i]=false;
bfs(v);
break;
case 3:
printf("Enter node to find adjacent vertices : ");
scanf("%d", &v);
printf("Adjacent Vertices are : ");
adj_nodes(v);
break;
case 4:
exit(1);
default:
printf("Wrong choice\n");
break;
}
}
}
create_graph()
{
int i,max_edges,origin,dest;
printf("Enter number of nodes : ");
scanf("%d",&n);
max_edges=n*(n-1);
for(i=1;i<=max_edges;i++)
{
printf("Enter edge %d( 0 0 to quit ) : ",i);
scanf("%d %d",&origin,&dest);
if((origin==0) && (dest==0))
break;
if( origin > n || dest > n || origin<=0 || dest<=0)
{
printf("Invalid edge!\n");
i--;
}
else
{
adj[origin][dest]=1;
}
}
return 0;
}
display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%4d",adj[i][j]);
printf("\n");
}
return 0;
}
bfs(int v)
{
int i,front,rear;
int que[20];
front=rear= -1;
printf("%d ",v);
visited[v]=true;
rear++;
front++;
que[rear]=v;
while(front<=rear)
{
v=que[front]; /* delete from queue */
front++;
for(i=1;i<=n;i++)
{
/* Check for adjacent unvisited nodes */
if( adj[v][i]==1 && visited[i]==false)
{
printf("%d ",i);
visited[i]=true;
rear++;
que[rear]=i;
}
}
}
return 0;
}
adj_nodes(int v)
{
int i;
for(i=1;i<=n;i++)
if(adj[v][i]==1)
printf("%d ",i);
printf("\n");
return 0;
}