-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbfs.c
More file actions
88 lines (78 loc) · 1.37 KB
/
bfs.c
File metadata and controls
88 lines (78 loc) · 1.37 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
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
void input(void);
int queueEmpty(void);
int dequeue(void);
void enqueue(int );
int v , arr[20][20] , queue[20] , visit[20] , start,front = -1,rear=-1;
void input(void)
{
for(int i = 0;i < v ; i++)
{
for(int j = 0 ; j < v ; j++)
scanf("%d",&arr[i][j]);
*(visit+i) = 0;
}
}
int dequeue(void){
int r;
if(front==rear){
r = queue[front];
front=rear=-1;
}else{
r = queue[front];
front++;
}
return r;
}
void enqueue(int pos){
if(rear==-1)
{
rear++;
front++;
}
else{
rear++;
}
queue[rear] = pos;
visit[pos] = 1;
}
int queueEmpty(void){
return front==-1 ? 1 : 0;
}
void bfs(){
printf("\nBFS of the graph : ");
enqueue(start);
while(!queueEmpty()){
int p = dequeue();
printf("%d ",p);
for(int i = 0 ; i < v ; i++){
if(arr[p][i]!=0 && visit[i]==0){
enqueue(i);
}
}
}
}
int main()
{
printf("\nEnter total no of vertices : ");
scanf("%d",&v);
printf("\nEnter the adj matrix : \n");
input();
printf("\nEnter the starting vertex : ");
scanf("%d",&start);
bfs();
}
/*
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0
0 1 1 0 0 0 0
1 0 0 1 1 0 0
1 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 1 0 0 0 0
*/