-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01 Breadth First Search.c
114 lines (100 loc) · 2.09 KB
/
01 Breadth First Search.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
#include<stdio.h>
#define INF 99999
int graph[10][10], s, num, i, j, front = 0, rear = 0;
int visited[10], d, previous[10], distance[10], queue[10], cycle = 0, count = 0;
void enqueue(int data)
{
queue[rear] = data;
rear++;
}
int dequeue()
{
/*int element;
element = queue[front];
front++;
return element;*/
return queue[front++];
}
int BFS()
{
int u, v;
for(u = 0; v < num; u++)
{
visited[u] = 0;
previous[u] = -1;
distance[u] = INF;
}
enqueue(s);
visited[s] = 1;
previous[s] = -1;
distance[s] = 0;
printf("Visiting Order: ");
while(rear != front)
{
u = dequeue();
printf("%d ", u);
count++;
for(v = 0; v < num; v++)
{
if(graph[u][v] == 1)
{
if(visited[v] == 0)
{
visited[v] = 1;
distance[v] = distance[u] + 1;
previous[v] = u;
enqueue(v);
}
else if(previous[u] != v)
{
cycle = 1;
break;
}
}
}
}
}
int main(void)
{
printf("Enter number of vertex: ");
scanf("%d", &num);
printf("Enter adjacency matrix:\n");
for(i = 0; i < num; i++)
{
for(j = 0; j < num; j++)
{
scanf("%d", &graph[i][j]);
}
}
printf("The adjacency matrix is:\n");
for(i = 0; i < num; i++)
{
for(j = 0; j < num; j++)
{
printf("%d ", graph[i][j]);
}
printf("\n");
}
printf("Enter source vertex:");
scanf("%d", &s);
printf("Enter destination vertex:");
scanf("%d", &d);
BFS();
printf("\nShortest Path: %d\n", distance[d]);
if(cycle == 1)
{
printf("Cycle Exit\n");
}
else if(cycle == 0)
{
printf("Cycle not found!\n");
}
if(count == num)
{
printf("Connected Graph!\n\n");
}
else if(count != num)
{
printf("Not Connected Graph!\n\n");
}
}