-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.c
78 lines (78 loc) · 1.4 KB
/
bfs.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
// to implement breadth first search
#include <stdio.h>
#include <stdlib.h>
typedef struct queue
{
int size;
int front;
int rear;
int *arr;
} queue; // end of structure definition
int isEmpty(queue *q)
{
if (q->front == q->rear)
return (1);
return (0);
} // end of fn.
int isFull(queue *q)
{
if (q->rear == q->size - 1)
return (1);
return (0);
} // end of fn.
void enqueue(queue *q, int val)
{
if (isFull(q))
printf("\nThe queue is full");
else
{
q->rear++;
q->arr[q->rear] = val;
} // end of if-else
} // end of fn.
int dequeue(queue *q)
{
int a = -1;
if (isEmpty(q))
printf("\nThe queue is empty");
else
{
q->front++;
a = q->arr[q->front];
} // end of if-else
return (a);
} // end of fn.
void main()
{
queue q;
q.size = 400;
q.front = q.rear = 0;
q.arr = (int *)malloc(q.size * sizeof(int));
int node;
int i = 0,j;
int visited[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int adj[8][8] = {
{0, 1, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0}};
printf("a ");
visited[i] = 1;
enqueue(&q, i);
while (!isEmpty(&q))
{
int node = dequeue(&q);
for (j = 0; j < 8; j++)
{
if (adj[node][j] == 1 && visited[j] == 0)
{
printf("%c ", (char)(j+97));
visited[j] = 1;
enqueue(&q, j);
} // end of if block
} // end of for loop
} // end of while loop
} // end of main