Professional Documents
Culture Documents
Breadth First Traversal - BFT
Breadth First Traversal - BFT
h>
#include<string.h>
#include<stdlib.h>
/*Queue has five properties. capacity stands for the maximum number of elements Queue can hold.
Size stands for the current size of the Queue and elements is the array of elements. front is the
index of first element (the index at which we remove the element) and rear is the index of last element
int capacity;
int size;
int front;
int rear;
int *elements;
}Queue;
/* crateQueue function takes argument the maximum number of elements the Queue can hold, creates
/* Create a Queue */
Queue *Q;
Q = (Queue *)malloc(sizeof(Queue));
Q->size = 0;
Q->capacity = maxElements;
Q->front = 0;
Q->rear = -1;
/* Return the pointer */
return Q;
if(Q->size==0)
printf("Queue is Empty\n");
return;
else
Q->size--;
Q->front++;
if(Q->front==Q->capacity)
Q->front=0;
return;
if(Q->size==0)
printf("Queue is Empty\n");
exit(0);
return Q->elements[Q->front];
/* If the Queue is full, we cannot push an element into it as there is no space for it.*/
if(Q->size == Q->capacity)
printf("Queue is Full\n");
else
Q->size++;
Q->rear = Q->rear + 1;
if(Q->rear == Q->capacity)
Q->rear = 0;
Q->elements[Q->rear] = element;
return;
void Bfs(int **graph, int *size, int presentVertex,int *visited, int V){
Queue *Q = CreateQueue(100);
Enqueue(Q, presentVertex);
visited[presentVertex] = 1;
int t, i;
while(!isEmpty(Q)){
t = Q->elements[Q->front];
Dequeue(Q);
printf("%d ",t);
Enqueue(Q, graph[t][i]);
visited[graph[t][i]] = 1;
int main()
int **graph,*size,*visited;
int vertices,edges,i;
int snode,enode;
char directed[4];
/* vertices represent number of vertices and edges represent number of edges in the graph. */
scanf("%d",&vertices);
scanf("%d",&edges);
scanf("%s",directed);
for(i=0;i<vertices;i++)
size = (int*)calloc(vertices,sizeof(int));
visited = (int*)calloc(vertices,sizeof(int));
for(i = 0;i<edges;i++)
scanf("%d%d",&snode,&enode);
if(strcmp(directed,"yes") == 0){
graph[snode][size[snode]++] = enode;
else{
graph[snode][size[snode]++] = enode;
graph[enode][size[enode]++] = snode;
}
}
int presentVertex;
scanf("%d",&presentVertex);
Bfs(graph,size,presentVertex,visited,vertices);
for(presentVertex=0;presentVertex<vertices;presentVertex++)
if(!visited[presentVertex])
Bfs(graph,size,presentVertex,visited,vertices);
return 0;