-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bfs.c
67 lines (54 loc) · 1.49 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
#include<stdio.h>
// creating queue data structure using arrays
int queue[100];
// defining pointers of the queue to perform pop and push
int front=0,back=0;
// defining push operation on the queue
void push(int var)
{
queue[back] = var;
back++;
}
// defining pop operation on queue
void pop()
{
queue[front] = 0;
front++;
}
// creating a visited array to keep the track of visited nodes
int visited[7] = {0};
int main()
{
// defining the number of total persons
int N = 6;
// adjacenty matrix representing graph
int graph[6][6] = {{0,1,1,0,0,0},
{1,0,1,0,0,0},
{1,1,0,1,1,0},
{0,0,1,0,0,0},
{0,0,1,0,0,1},
{0,0,0,0,1,0}};
// front == back stands for empty queue
// until queue is not empty perfroming bfs
// adding a starting node in the list
push(1);
visited[0] = 1; // marking 1st node as visited
while(front != back)
{
int current = queue[front];
// printing current element
printf("%d ", current);
// popping the front element from the queue
pop();
for(int i=0;i<6;i++)
{
// adding non-visited connected nodes of the current node to the queue
if((graph[current-1][i] == 1) && (visited[i] == 0))
{
visited[i] = 1; // marking visisted
push(i+1);
}
}
}
return 0;
}