-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS.cpp
71 lines (67 loc) · 1.47 KB
/
BFS.cpp
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
#include<stdio.h>
/*Adjacency Matrix*/
int G[6][6] = {{0,1,0,1,0,1},
{1,0,1,0,0,0},
{0,1,0,0,0,0},
{1,0,0,0,1,0},
{0,0,0,1,0,1},
{1,0,0,1,1,0}};
/*Stack*/
int queue[100], start = -1,end = -1;
void enqueue(int val)
{if(start == -1)
{start++;
end++;
queue[end] = val;
}
else
{end++;
queue[end] = val;
}
}
int dequeue()
{start++;
return queue[start-1];
}
void state()
{for(int i=start; i<=end; i++)
printf("%d ",queue[i]);
}
/*DFS Function*/
void BFS(int n, int source)
{int BFS_Order[n];
int vertex_state[n];
for(int i=0;i<n;i++)
vertex_state[i] = 0; /*0 - not visited, 1 - under process, 2 - processed*/
enqueue(source-1);
vertex_state[source-1] = 1;
int index = 0;
printf("Initial Queue State: ");
state();
printf("\n");
while(start <= end)
{int v = dequeue();
vertex_state[v] = 2;
BFS_Order[index] = v+1;
index++;
for(int j=0;j<n;j++)
{if(G[v][j] !=0 && vertex_state[j] == 0) /*Vertices adjacent to reently popped vertex v which are not processed*/
{enqueue(j);
vertex_state[j] = 1;
}
}
printf("Queue State at Iteration %d : ",index);
state();
printf("\n");
}
printf("\nBreadth First Search Order : ");
for(int i=0;i<n;i++)
printf("%d ",BFS_Order[i]);
}
int main()
{int source;
printf("Enter Source Vertex : ");
scanf("%d",&source);
BFS(6,source);
return 0;
}